相似於DOM事件處理,有幾點不一樣之處:html
例子,HTML:react
<button onclick="activateLasers()"> Activate Lasers </button>
React:git
<button onClick={activateLasers}> Activate Lasers </button>
false
來阻止事件的默認行爲,必須調用preventDefault
函數。例子,HTML:github
<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定義一個組件的時候,事件監聽器是做爲一個類方法存在的。 例以下面的Toggle
組件,能夠在「ON」和「OFF」之間切換:this
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回調裏面的那個this
:code
在js裏面,類方法默認是沒有綁定(bound)的,加入你忘記了綁定this.handleClick
,而後把它傳給onClick
,當函數被調用的時候,this
將會是undefined
。htm
這不是React的特有行爲,能夠參考這篇文章。 一般,在使用方法的時候,後面沒有加()
,例如onClick={this.handleClick}
,這時你就要綁定這個方法。blog
若是你不想調用bind
,仍是有兩種方法能夠繞過的。
第一種是使用實驗性的屬性初始化語法(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> ); } }
這種語法的問題是,每次渲染LoggingButton
的時候,都會建立不一樣的回調函數。 大部分狀況下,這是沒有問題的。可是,若是這個回調函數是做爲一個prop
傳遞給下層組件的話,這些組件會重複渲染。 一般的推薦方法是在constructor
裏面綁定,以免這種性能問題。
參考連接:
- React Doc:handling events