1.props,通过this.props我们可以拿到组件使用时的属性。
var HelloWorld = React.createClass({
render: function () {
return (
<div data-title={this.props.title}>{this.props.content}</div>
)
}
});
React.render(
<HelloWorld title="this is title" content="this is content"/>,
document.body
);
2.获取子节点的属性 this.props.children
var HelloWorld = React.createClass({
render: function () {
return (
<div>
{
this.props.children.map(function (child) {
return child;
})}
</div>
)
}
});
React.render(
<HelloWorld title="this is title">
<span>1</span>
<span>2</span>
</HelloWorld>,
document.body
);
3.state 是同UI交互最重要的属性
var ColorButton = React.createClass({
getInitialState: function () {
return {bColor: 'green'};
},
render: function () {
return (
<button onClick={this.handleClick} style={{backgroundColor: this.state.bColor}}>click</button>
)
},
handleClick: function (event) {
this.setState({bColor: this.state.bColor === 'green' ? 'red' : 'green'});
}
});
React.render(
<ColorButton />,
document.body
);
4.自动绑定
所有的事件处理函数当中的this指向组件的实例。如果想要拿到当前操作的DOM,通过参数event获取。
var ColorButton = React.createClass({
getInitialState: function () {
return {name: 'button'};
},
render: function () {
return (
<button onClick={this.handleClick}>click</button>
)
},
handleClick: function (event) {
console.log(this.state);
console.log(event.target);
}
});
React.render(
<ColorButton />,
document.body
)