【问题标题】:what is a different approach to bind a function to a component React es6 [duplicate]将函数绑定到组件 React es6 的不同方法是什么 [重复]
【发布时间】:2017-09-09 06:31:24
【问题描述】:

我有一个像示例中一样的组件

class ItemBox extends Component {

  constructor(props){
    super(props);
    this.someFn = this.someFn.bind(this);
  }

  someFn(){
    console.log(this)
  }

  render(){
    return (
      <div onClick={this.someFn}>bla<div/>
    )
  }
};

我想问 - 是否有某种不同的解决方案将函数绑定到组件,除了我在构造函数中使用(从文档中阅读)。因为我可以有 100 个函数传递给子组件或在这个组件中使用等等。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    你可以这样做...

    class ItemBox extends Component {
    
      someFn = ()=>{
        console.log(this)
      }
      constructor(props){
        super(props);
      }
    
      render(){
        return (
          <div onClick={this.someFn}>bla<div/>
        )
      }
    };
    

    【讨论】:

      【解决方案2】:

      我通常这样做:

      class SomeComponent extends Component {
          _handleClick = () => {
               console.log(this)
          }
          render() {
              return (
                  <div onClick={this._handleClick}>bla</div>
              )
          } 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-03
        • 2020-11-15
        • 2016-05-19
        • 2016-11-10
        • 2017-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多