创建组件基本原则:
1. 组件名首字母大写
2. 组件只能包含一个根节点
方法1(基于dva,即状态均由dva控制):
function Test() {
return (
<div>test</div>
)
}
方法2:
var Test = React.createClase({
getDefaultProps : function () { // 设置组件属性的默认值
return {
title : 'Hello World'
};
},
getInitialState: function() { // 设置组件的状态
return {name: 'ttt'};
},
updateState: function() { // 更新组件状态
this.setState({name: 'xxx'});
},
render: function() {
return (
<div>
<span>this.props.title</span>
<span>this.state.name</span>
<span onClick={this.updateState}>click</span>
</div>
);
}
});
方法3:
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {name: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({temperature: e.target.value});
}
render() {
return (
<div>
<span>this.props.title</span>
<span>this.state.name</span>
<span onClick={this.updateState}>click</span>
</div>
);
}
}