使用.bind(this)
.bind(this)
是最常用的绑定方式,直接手动绑定到this上
在使用位置绑定
import React from 'react';
import ReactDOM from 'react-dom';
class LoggingButton extends React.Component {
handleClick(){
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick.bind(this)}>
Click me
</button>
);
}
}
ReactDOM.render(<LoggingButton/>,document.getElementById('root'));
在构造函数中绑定
import React from 'react';
import ReactDOM from 'react-dom';
class LoggingButton extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
ReactDOM.render(<LoggingButton />, document.getElementById('root'));
使用箭头函数
箭头函数的方式是ES6+里面的
使用处用箭头函数包裹
import React from 'react';
import ReactDOM from 'react-dom';
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
return (
<button onClick={()=>this.handleClick()}>
Click me
</button>
);
}
}
ReactDOM.render(<LoggingButton />, document.getElementById('root'));
类处使用箭头函数
import React from 'react';
import ReactDOM from 'react-dom';
class LoggingButton extends React.Component {
handleClick = () => {
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
ReactDOM.render(<LoggingButton />, document.getElementById('root'));