传统HTML中
<div onclick="handleclick()"></div>
handleclick函数自动绑定了this,而react中<div onClick={handleclick}"></div>
需要手动绑定,下面是回调函数绑定this的三种方法- bind(this)
constructor(props){
super(props);
this.state={};
this.functionname=this.functionname.bind(this);
}
- 属性初始化器
functionname(){
console.log("this is",this);
//function here...
}
- 箭头函数
render(){
return(
<div onClick={(e)=>(this.function(e))}></div>
)
}
- HTML中阻止事件的默认行为可以用
return false
<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
</a>
而React中只能显示调用e.preventDefault();
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
- 组件可以用函数和类定义,但是只有类定义的组件有局部状态和生命周期钩子. this.props 和 this.state 可能是异步更新的,不应该依靠它们的值来计算下一个状态。例如,此代码可能无法更新计数器:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
要修复它,请使用第二种形式的 setState() 来接受一个函数而不是一个对象。 该函数将接收先前的状态作为第一个参数,将需要更新的值作为第二个参数:
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
- 组件生命周期
React Component通过其定义的几个函数来控制组件在生命周期的各个阶段的动作。
constructor(props, context)
构造函数,在创建组件的时候调用一次。
void componentWillMount()
在组件挂载之前调用一次。如果在这个函数里面调用setState,本次的render函数可以看到更新后的state,并且只渲染一次。
void componentDidMount()
在组件挂载之后调用一次。这个时候,子组件也都挂载好了,可以在这里使用refs。
void componentWillReceiveProps(nextProps)
props是父组件传递给子组件的。父组件发生render的时候子组件就会调用componentWillReceiveProps(不管props有没有更新,也不管父子组件之间有没有数据交换)。
bool shouldComponentUpdate(nextProps, nextState)
组件挂载之后,每次调用setState后都会调shouldComponentUpdate判断是否需要重新渲染组件。默认返回true,需要重新render。在比较复杂的应用里,有一些数据的改变并不影响界面展示,可以在这里做判断,优化渲染效率。
void componentWillUpdate(nextProps, nextState)
shouldComponentUpdate返回true或者调用this.forceUpdate()之后,componentWillUpdate会被调用。
void componentDidUpdate()
除了首次render之后调用componentDidMount,其它render结束之后都是调用componentDidUpdate。
componentWillMount、componentDidMount和componentWillUpdate、componentDidUpdate可以对应起来。区别在于,前者只有在挂载的时候会被调用;而后者在以后的每次更新渲染之后都会被调用。
ReactElement render()
render是一个React组件所必不可少的核心函数(上面的其它函数都不是必须的)。记住,不要在render里面修改state。
void componentWillUnmount()
组件被卸载的时候调用。一般在componentDidMount里面注册的事件需要在这里删除。
在react中,触发render的有4条路径。
以下假设shouldComponentUpdate都是按照默认返回true的方式。
- 首次渲染Initial Render
- 调用this.setState (并不是一次setState会触发一次render,React可能会合并操作,再一次性进行render)
- 父组件发生更新render(一般就是props发生改变,但是就算props没有改变或者父子组件之间没有数据交换也会触发render)
- 调用this.forceUpdate()