题目:页面输出【学习react】点击切换为【学习vue】,点击来回切换
class Study extends React.Component {
constructor(props) {
super(props);
this.state = {frameType: false};
this.tick = this.tick.bind(this);
}
tick() {
this.setState({frameType: !this.state.frameType});
}
render() {
const frameType = this.state.frameType;
return (<div onClick={this.tick}><h2>学习{frameType ? 'react' : 'vue'}</h2></div>)
}
}
标准的写法注意点:
- 类组件的方法都是事件行为
- 类组件中的方法不能使用this,必须绑定类,
this.tick = this.tick.bind(this);
- render能使用this是因为react框架默认已经绑定好了
- render中使用的事件行为tick,不是类中的方法tick,而是类属性tick。绑定事件中的this.tick
标红的举例如下
class Study extends React.Component {
constructor(props) {
super(props);
this.state = {frameType: false};
this.change = this.tick.bind(this);
}
tick() {
this.setState({frameType: !this.state.frameType});
}
render() {
const frameType = this.state.frameType;
return (<div onClick={this.change}><h2>学习{frameType ? 'react' : 'vue'}</h2></div>)
}
}
这个得知道,但一般我们写代码的时候,都重名就可以了
下面对该标准写法做优化处理
class Study extends React.Component {
state={frameType:false};
tick=()=>{
this.setState({frameType: !this.state.frameType});
}
render() {
const frameType = this.state.frameType;
return (<div onClick={this.tick}><h2>学习{frameType ? 'react' : 'vue'}</h2></div>)
}
}
- 箭头函数有一个重要的特点,是自身没有this,但可以使用this,它会往上找this,哪怕找到windows,但绝不会是undefined。所以在组件类中定义事件行为的时候,使用箭头函数,this就是指向该组件实例了。
- 类有一个基本概念,属性可以直接在类中定义,而不需要在构造函数中定义。所以state也可以直接写在类中