React的组件需要和用户互动,需要修改state,当state的状态发现改变的时候,就会触发重新渲染UI。
代码:
export class ModeButton extends React.Component {
constructor(props) {
super(props);
this.state = {
touchState: true
}
}
touchStart() {
console.log("touch");
// this.setState() 给属性复制,只用通过setState这个方法触发才会刷新View层
this.setState({touchState: !this.state.touchState});
}
render() {
var src = '../images/' + "childlock" + (this.state.touchState? '-on' : '-off') + '@3x.png';
return <div className={this.props.className} onTouchStart={this.touchStart.bind(this)}>
<img src={src} />
<p >{this.props.text}</p>
</div>;
}
};
使用:
<div>
<p>About me!!!!!</p>
<ModeButton className="modeButton" text = "开关"/>
</div>
这里涉及到react的几个知识点:
1、props
2、state
props就是可以从上级节点继承过来的属性,就是属性和组件一一对应。
className从外面传进来,方便外面做CSS布局
text也从外面赋值,增加灵活性
state是用来实现动态刷新界面的。onTouchStart绑定 touchStart()函数
使用了setState() 才会重绘
网友评论