react绑定事件

绑定事件

  • React事件名区别于DOM事件,以驼峰命名法
  • JSX以函数的方式传递时间,而不是字符串
//HTML:

<button onclick="activateLasers()">
  Activate Lasers
</button>

//React:
<button onClick={activateLasers}>
  Activate Lasers
</button>
  • React中只能用preventDefault阻止默认行为,不可以用 return false
//HTML
<a href="#" onclick="console.log('The link was clicked.'); return false">
  Click me
</a>

//React
function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}
  • JSX回调中的this问题

必须在回调函数constructor中给事件回调函数绑定this,否则会报undefined

本章示例

constructor中绑定this,点击按钮切换ONOFF

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

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

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

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

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

你可能感兴趣的:(react)