事件处理
React允许开发人员为虚拟DOM添加事件处理操作,而后在render之后就会将事件绑定到真实的DOM上。而不同的是,虚拟DOM上的事件与原生的事件的写法是不一样的,如原生的onclick而在React中要使用onClick。而事件绑定的属性值为一个自定义事件函数函数名,会在render的时候自行调用。
<button onClick={this.showInput}>提示输入</button>
<input onBlur={this.handleBlur} type="text" placeholder="失去焦点提示内容"/>
而事件函数只需要额外写出即可,但是有一个问题所在,即事件没有this,直接打印的this为undefined,需要在constructor中为函数指定this为组件对象。
constructor(props){
super(props);
this.showInput = this.showInput.bind(this);
this.handleBlur = this.handleBlur.bind(this);
}
下面给出我的完整代码,分别定义了showInput和handleBlur两个事件,再点击提示框时和失去焦点时触发。并分别为函数绑定了this并赋值给原来的函数,完整代码如下:
//1.定义组件
class MyTips extends React.Component{
constructor(props){
super(props);
this.showInput = this.showInput.bind(this);
this.handleBlur = this.handleBlur.bind(this);
}
showInput(){
alert(this.input.value)
}
handleBlur(event){
alert(event.target.value)
}
render(){
return(
<div>
<input type="text" ref={(input)=>this.input = input} />
<button onClick={this.showInput}>提示输入</button>
<input onBlur={this.handleBlur} type="text" placeholder="失去焦点提示内容"/>
</div>
)
}
}
//2.渲染组件标签
ReactDOM.render(<MyTips/>,document.getElementById('demo'));
React的生命周期
与vue一样,React也有自己的生命周期,即该组件从开始创建直至死亡,在各个阶段,均有自己的生命周期的钩子函数,会在特定的时期,调用对应的钩子函数实现特定的功能。比如在组件初始化的时候去请求服务器数据进行展示,在组件销毁的时候清除定时器等操作。
1、组件初始化
在组建初始化时,会先后调用componentWillMount ,componentDidMount 和componentWillReceiveProps ,分别在渲染之前,第一次渲染后和接收新的prop时。
componentWillMount 在渲染前调用,在客户端也在服务端。
componentDidMount 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。
componentWillReceiveProps 在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用。
2、组件更新
在组件进行更新时都会调用一次,比如props或state进行数据的更新时都会去调用一次render方法,同时相关的生命周期的钩子函数(shouldComponentUpdate ,componentWillUpdate和componentDidUpdate )也会相应的被调用。
shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。 可以在你确认不需要更新组件时使用。
componentWillUpdate在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。
componentDidUpdate 在组件完成更新后立即调用。在初始化时不会被调用。
3、组件销毁
componentWillUnmount在组件从 DOM 中移除之前立刻被调用。
class Button extends React.Component {
componentWillMount() {
console.log('Component WILL MOUNT!')
}
componentDidMount() {
console.log('Component DID MOUNT!')
}
componentWillReceiveProps(newProps) {
console.log('Component WILL RECEIVE PROPS!')
}
componentWillUpdate(nextProps, nextState) {
console.log('Component WILL UPDATE!');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component DID UPDATE!')
}
componentWillUnmount() {
console.log('Component WILL UNMOUNT!')
}
render() {
return (
<div>
<h3 onClick={this.setState({myNumber:this.props.myNumber++})}>{this.props.myNumber}</h3>
</div>
);
}
}
ReactDOM.render(<Button />,document.getElementById('example'));