加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react中的事件处理

发布时间:2020-12-15 09:33:35 所属栏目:百科 来源:网络整理
导读:一、使用bind绑定this class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; // 为了在回调中使用 `this`,这个绑定是必不可少的 this.handleClick = this.handleClick.bind(this); } handleClick(

一、使用bind绑定this

class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};

// 为了在回调中使用 `this`,这个绑定是必不可少的
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}

render() {
return (
  <button onClick={this.handleClick}>
    {this.state.isToggleOn ? ‘ON‘ : ‘OFF‘}
     </button>
  );
}
}

ReactDOM.render(
  <Toggle />,
document.getElementById(‘root‘)
);

二、class fields语法

class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
}
  //class fields语法
handleClick = () => {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}

render() {
return (
<button onClick={this.handleClick}>
    {this.state.isToggleOn ? ‘ON‘ : ‘OFF‘}
    </button>
  );
}
}

ReactDOM.render(
  <Toggle />,
document.getElementById(‘root‘)
);

三、在回调中使用箭头函数

class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
}

handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}

render() {
return (
<button onClick={(e) => this.handleClick(e)}>
    {this.state.isToggleOn ? ‘ON‘ : ‘OFF‘}
    </button>
  );
}
}

ReactDOM.render(
  <Toggle />,
document.getElementById(‘root‘)
);

注意:语法3中回调函数作为props传入子组件时,这些组件可能会额外重新渲染,所以我们建议使用1、2语法来避免出现性能问题

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读