多个组件合成一个组件:
var style = { fontSize: 20, color: '#ff0000' }; var WebSite = React.createClass({ render: function () { return ( <div style={style}> <Name name={this.props.name} /> <Link link={this.props.link} /> </div> ); } }); var Name = React.createClass({ render: function () { return ( <h1>{this.props.name}</h1> ); } }); var Link = React.createClass({ render: function () { return ( <a href={this.props.link}>{this.props.link}</a> ) } }); React.render(<WebSite name="lqc" link="www.baidu.com" />, document.getElementById('example'));
State状态
getInitialState: function () { return {object: false;} }
this.setState({object: !this.state.object});
var LikeButton = React.createClass({ getInitialState: function () { return {liked: false}; }, handleClick: function (event) { this.setState({liked: !this.state.liked}); }, render: function () { var text = this.state.liked ? '喜欢' : '不喜欢'; return ( <p onClick={this.handleClick}> 你<b>{text}</b>我。点我切换状态。 </p> ); } }); React.render(<LikeButton/>, document.getElementById('example'));
默认的props
var MyMessage = React.createClass({ getDefaultProps: function () { return { name: 'runoob' } }, render: function () { return <h1>{this.props.name}</h1> } }); React.render(<MyMessage/>, document.getElementById('example'));
state和props混合使用
var Website = React.createClass({ getInitialState: function () { return { name: "百度", link: 'http://www.baidu.com' } }, render: function () { return ( <div> <Name name={this.state.name} /> <Link link={this.state.link} /> </div> ); } }); // 构建下面两个组件的数据用props var Name = React.createClass({ render: function () { return ( <h1>{this.props.name}</h1> ) } }); var Link = React.createClass({ render: function () { return ( <a href={this.props.link}>{this.props.link}</a> ) } }); React.render(<Website />, document.getElementById('example'));
Props验证使用propTypes
propTypes: {
title: React.PropTypes.string.isRequired
}
多个组件渲染可以写在同一页面:
var Website = React.createClass({ getInitialState: function () { return { name: "百度", link: 'http://www.baidu.com' } }, render: function () { return ( <div> <Name name={this.state.name} /> <Link link={this.state.link} /> </div> ); } }); // 构建下面两个组件的数据用props var Name = React.createClass({ render: function () { return ( <h1>{this.props.name}</h1> ) } }); var Link = React.createClass({ render: function () { return ( <a href={this.props.link}>{this.props.link}</a> ) } }); React.render(<Website />, document.getElementById('example')); // Props验证使用propTypes var title= 'React'; var MyTitle = React.createClass({ propTypes: { title: React.PropTypes.string.isRequired }, render: function () { return ( <h1>{this.props.title}</h1> ) } }); React.render(<MyTitle title={title} />, document.getElementById('example2'));
下一节:
React组件的生命周期