【问题标题】:Re-usable base React component bind issue with ES6ES6 的可重用基础 React 组件绑定问题
【发布时间】:2015-11-30 22:26:56
【问题描述】:

创建了一个基础的 React 组件来继承:

import { Component } from 'react';

class BaseComponent extends Component {
    constructor(props) {
        super(props);
    }

    _bindProps(...methods) {
        return methods.map(method => this[method].bind(this))
    }
}

export default BaseComponent;

还有我的子组件:

class SomeChild extends BaseComponent {

    constructor(props) {
        super(props);
    }

    foo() {

    }

    render() {
        const props = this._bindProps('foo');
        <Child {...props} />
    }
}

但是,我在return methods.map(method =&gt; this[method].bind(this)) 线上收到了Cannot read property 'bind' of undefined。我怎样才能做到这一点,即。将方法从父组件传递给子组件,当从子组件调用时,让其 this 值引用父组件。

【问题讨论】:

    标签: reactjs bind ecmascript-6


    【解决方案1】:

    class SomeChild extends BaseComponent {
    
        constructor(props) {
            super(props);
        }
    
        foo = () => {
    
        }
    
        render() {
            <Child foo={this.foo} />
        }
    }

    如果您只是使用 BaseComponent 将(this)绑定到方法并使用 es6,那么为您的方法使用箭头函数会更简单。

    【讨论】:

    • 是的,我看到了。我将如何为此目的使用箭头功能? IE。将方法向下传递给组件
    • 请记住箭头函数不会绑定在原型上。
    【解决方案2】:

    Janaka 仅使用箭头函数是正确的,但您的 _bindProps 实现也存在问题。它返回一个绑定函数数组,但您需要返回一个 key/val 属性对象。将您的 _bindProps 定义更新为:

    _bindProps(obj) {
      Object.keys(obj).forEach(k => obj[k] = obj[k].bind(this));
      return obj;
    }
    

    用一个对象调用它就可以了:

    class BaseComponent extends React.Component {
      constructor(props) {
        super(props);
      }
    
      _bindProps(obj) {
        Object.keys(obj).forEach(k => obj[k] = obj[k].bind(this));
        return obj;
      }
    }
    
    class SomeChild extends BaseComponent {
    
      constructor(props) {
        super(props);
        this.name = 'Jack'
      }
    
      foo() {
        return this.name;
      }
    
      render() {
        const props = this._bindProps({
          foo: this.foo,
        });
        console.log('props', props);
        return <Child {...props} />
      }
    }
    

    您可以稍微整理一下上面的内容,但现在这样做是正确的,如果您在子组件中调用 this.props.foo(),您将返回 Jack

    我很想知道您为什么要这样做?这不是我通常在任何时候都必须做的事情。

    【讨论】:

    • 对于基本相同的组件,我基本上有两个不同的“视图”(忘记 MVC 视图,我的意思是字面意思)。所以我创建了两个子组件(对于每个“视图”),然后将所有回调方法从 1 个父级传递给 2 个子级。事件处理程序添加在子级中,但它们实际上调用父级中的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多