var Divider =React.createClass({
getInitialState:function(){
return {props:true}
},
handleClick:function(){
this.setState({props:!this.state.props})
console.log(this.state.props)
},
render:function(){
var classString = 'content' + (this.state.props ? ' bg-red' : ' bg-green');
return (
<div>
<h2 className={classString}>{this.props.children}</h2>
<button onClick={this.handleClick}>点击变色</button>
</div>
)
}
})
ReactDOM.render(
// <WebSite name="11111" site="123456" />,
<Divider>Jasper</Divider>,
// <h1>jasper</h1>,
document.getElementById('root')
getInitialState:function(){
return {props:true}
},
handleClick:function(){
this.setState({props:!this.state.props})
console.log(this.state.props)
},
render:function(){
var classString = 'content' + (this.state.props ? ' bg-red' : ' bg-green');
return (
<div>
<h2 className={classString}>{this.props.children}</h2>
<button onClick={this.handleClick}>点击变色</button>
</div>
)
}
})
ReactDOM.render(
// <WebSite name="11111" site="123456" />,
<Divider>Jasper</Divider>,
// <h1>jasper</h1>,
document.getElementById('root')
);
开始直接写在点击时间里没有使用setState,这时虽然点击后能来回实现props的值来回切换,但是并不能传入render中
getInitialState 用来定义初始化状态 ,也就是一个对象,这个对象可以通过 this.state 属性读取。
this.setState
方法就修改状态值,每次修改以后,自动调用 this.render 方法,再次渲染组件。
所以再用这个属性改变值可以动态渲染组件
从而实现toggle效果