reactjs 将函数绑定到React函数组件的示例

cbjzeqam  于 2023-05-17  发布在  React
关注(0)|答案(1)|浏览(108)

我从https://legacy.reactjs.org/docs/faq-functions.html中找到了这个代码片段,它将函数绑定到React组件的特定示例:

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>;
  }
}

我可以使用函数组件来做类似的事情吗?
我在函数组件中尝试过这个方法(将this.handleClick = this.handleClick.bind(this);移出构造函数),但是this(在语句中)返回undefined而不是函数组件。

68bkxrlz

68bkxrlz1#

React中的绑定方法并没有做你认为它在做的事情。
this.someMethod.bind(this)用于将方法绑定到类(而不是子组件),因此方法可以访问props和state。
当我们得到类属性时,就不再需要了(方法使用箭头函数语法)。
对于函数组件,它也完全无关紧要,因为当函数定义和使用在同一个函数组件中时,就没有范围问题了。
所以这三个都做同样的事情:

class Foo extends React.Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick () {
    console.log('clicked')
  }
  render() {
    return <button onClick={this.handleClick}>click</button>
  }
}

class Foo extends React.Component {
  handleClick = () => { console.log('clicked') }
  render() {
    return <button onClick={this.handleClick}>click</button>
  }
}

const Foo = () => {
  const handleClick = () => { console.log('clicked') }
  return <button onClick={handleClick}>click</button>
}

相关问题