react事件處理,為類方法繫結this
阿新 • • 發佈:2019-01-01
- react事件繫結屬性的命名採用駝峰命名法,
- 如果採用JSX的語法,需要傳入一個函式作為事件處理函式,而不是一個字串(DOM元素的寫法)。
阻止事件的預設行為:
- 不能使用返回false的方式來阻止預設行為,必須明確的使用preventDefault
在類方法中繫結this
注:要謹慎的在類方法中使用this,因為類方法預設不會繫結this。需要主動的將這類方法繫結到this上。
為類方法上繫結this的方法:
- 在構造方法中為類方法繫結this
class LoggingButton extends React.Component { constructor(props){ super(props); //類方法,必須為每個類方法繫結this,否則在類方法總使用this時,會是undefined this.handleClick = this.handleClick.bind(this); } handleClick(){ console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
- 屬性初始化器語法
class LoggingButton extends React.Component { // 這個語法確保了 `this` 繫結在 handleClick 中 // 這裡只是一個測試 handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
- 調函式中使用 箭頭函式:
class LoggingButton extends React.Component { handleClick() { console.log('this is:', this); } render() { // 這個語法確保了 `this` 繫結在 handleClick 中 return ( <button onClick={(e) => this.handleClick(e)}> Click me </button> ); } }