在react中實現(xiàn)事件處理,有如下幾種
第一種:在constructor函數(shù)中用bind方法
class ReactEvent extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
第二種:使用箭頭函數(shù)(render中使用箭頭函數(shù))
class ReactEvent extends Component {
handleClick() {
console.log('Click');
}
render() {
return <button onClick={() => this.handleClick()}>Click Me</button>;
}
}
第三種:使用class fields語法
class ReactEvent extends Component {
handleClick = () => {
console.log('Click');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
第四種:在render中使用bind方法
class ReactEvent extends Component {
handleClick() {
console.log('Click');
}
render() {
return <button onClick={this.handleClick.bind(this)}>Click Me</button>;
}
}
幾種方式的比較
| 影響 | constructor函數(shù)中bind | 使用class fields語法 | render中使用箭頭函數(shù) | 在render中使用bind |
|---|---|---|---|---|
| render時生成新函數(shù) | 否 | 否 | 是 | 是 |
| 性能 | 無影響 | 無影響 | 有影響 | 有影響 |
| 可直接攜帶參數(shù) | 否 | 否 | 是 | 是 |
在render中直接bind或者箭頭函數(shù)都會影響性能,原因在于,在render 中的bind和箭頭函數(shù)在每次render時都會創(chuàng)建新的函數(shù),導(dǎo)致子組件的props發(fā)生改變,這在PureComponent中會影響性能,除非自己在shouldComponentUpdate中進行優(yōu)化。
參數(shù)傳遞
直接傳遞參數(shù),render中使用箭頭函數(shù)
this.state.list.map(item => (
<Button onClick={() => this.handleClick(item.id)}/>
))
直接傳遞參數(shù),render中使用bind
this.state.list.map(item => (
<Button onClick={this.handleClick.bind(this, item.id)}/>
))
推薦的方式
//子組件
class Button extends React.PureComponent {
handleClick = () => {
this.props.handleClick(this.props.item);
}
render() {
return (
<button onClick={this.handleClick}>hello world</button>
)
}
}
//父組件
class ButtonList extends React.Component {
constructor(props) {
super(props);
this.state = {
list: [1, 2, 3, 4]
};
}
handleClick = (item) => {
console.log('Click', item);
}
render() {
const { list=[] } = this.state;
return (
<div>
{
list.map(item => <Button handleClick={this.handleClick} item={item}/>)
}
</div>
)
}
}