1. 程式人生 > >react 之 將函式繫結到元件例項

react 之 將函式繫結到元件例項

1. 在Constructor中繫結(ES2015) 2. 類屬性(第三階段提案) 3. 在Render中使用bind繫結 4. 在Render中使用箭頭函式

在Constructor中繫結(ES2015)

class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log('Click happened');
  }
  render() {
    return
<button onClick={this.handleClick}>Click Me</button>; } }

類屬性(第三階段提案)

class Foo extends Component {
  // Note: this syntax is experimental and not standardized yet.
  handleClick = () => {
    console.log('Click happened');
  }
  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

在Render中使用bind繫結

class Foo extends Component {
  handleClick() {
    console.log('Click happened');
  }
  render() {
    return <button onClick={this.handleClick.bind(this)}>Click Me</button>;
  }
}

在Render中使用箭頭函式

class Foo extends Component {
  handleClick() {
    console.log('Click happened'
); } render() { return <button onClick={() => this.handleClick()}>Click Me</button>; } }