【问题标题】:i got this interview question and i am not sure what is best answer When in the lifecycle would you bind to events? in reactjs [closed]我收到了这个面试问题,但我不确定最佳答案是什么?在生命周期中,您何时会绑定到事件?在 reactjs [关闭]
【发布时间】:2019-01-04 21:11:12
【问题描述】:

您会在生命周期中的什么时候绑定事件?在 reactjs 中

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    想象一下组件中的点击处理程序:

    import * as React from 'react';
    
    class SomeComponent extends React.Component {
      handleClick(e) {
        this.setState({ clicked: true });
      }
    
      render() {
        return <button onClick={this.handleClick}/>;
      }
    }
    

    显然这不起作用,因为当handleClick 被调用时,this 没有被设置为组件实例。现在考虑以下替代方案:

    render() {
      return <button onClick={this.handleClick.bind(this)}/>;
    }
    

    这样,您就可以在每次渲染时创建一个新版本的函数。与此相同:

    render() {
      return <button onClick={e => this.handleClick(e)}/>;
    }
    

    ...所以一种更有效的方法是在构造函数中绑定:

    class SomeComponent extends React.Component {
      constructor() {
        super(...arguments);
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick(e) {
        this.setState({ clicked: true });
      }
    
      render() {
        return <button onClick={this.handleClick}/>;
      }
    }
    

    ...但这并不是普遍认为的最佳实践。如果你仍然使用babel,你可以使用 ECMAScript 提议的类实例属性:

    class SomeComponent extends React.Component {
      constructor() {
        super(...arguments);
      }
    
      handleClick = e => {
        this.setState({ clicked: true });
      };
    
      render() {
        return <button onClick={handleClick}/>;
      }
    }
    

    ...它将自动将this 绑定到实例。

    但简而言之,面试官可能希望你说“在构造函数中”。

    【讨论】:

    • 非常感谢您的回答,您说得简单明了
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多