React - 事件处理
类似于DOM事件处理,有几点不同之处:
例子,HTML: <button onclick="activateLasers()"> Activate Lasers </button> React: <button onClick={activateLasers}> Activate Lasers </button>
例子,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> ); } 使用React不需要再DOM创建之后给事件添加监听器,仅需在渲染的时候提供监听器即可。 用ES6的class定义一个组件的时候,事件监听器是作为一个类方法存在的。 例如下面的 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') ); 关于JSX回调里面的那个 在js里面,类方法默认是没有绑定(bound)的,加入你忘记了绑定 这不是React的特有行为,可以参考这篇文章。 通常,在使用方法的时候,后面没有加 如果你不想调用 第一种是使用实验性的属性初始化语法(property initializer syntax),用属性初始化来绑定回调函数: class LoggingButton extends React.Component { // This syntax ensures `this` is bound within handleClick. // Warning: this is *experimental* syntax. // 确保'this'和handleClick绑定,这还是实验性的语法 handleClick = () => { console.log('this is:',this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } } 这个语法在React里面是默认可用的。 第二种方法是使用箭头函数(arrow function)。 class LoggingButton extends React.Component { handleClick() { console.log('this is:',this); } render() { // This syntax ensures `this` is bound within handleClick // 确保'this'和handleClick绑定 return ( <button onClick={(e) => this.handleClick(e)}> Click me </button> ); } } 这种语法的问题是,每次渲染
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |