可重新启用的基数与ES6的反应组件绑定问题 [英] Re-usable base React component bind issue with ES6
问题描述
创建一个基本的React组件继承自:
Created a base React component to inherit from:
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} />
}
}
但是,我收到不能在
。我怎么能达到这个,即将方法从父组件传递给孩子,当从孩子调用它时,它的行读取未定义的
的属性'bind'返回methods.map(method => this [method] .bind(this))这个
值引用父组件。
However, I receive Cannot read property 'bind' of undefined
on the line return methods.map(method => this[method].bind(this))
. How can I achieve this, ie. passing down methods from a parent component to a child, and when it's called from the child, have it's this
value reference the parent component.
推荐答案
Janaka是正确的使用箭头函数,但你也有一个问题,你的 _bindProps
实现。它返回一个绑定函数的数组,但是你需要返回一个key / val对象的属性。将 _bindProps
定义更新为:
Janaka is right about just using arrow functions, but also you've a problem with your _bindProps
implementation. It returns an array of bound functions but you need to return a key/val object of properties. Updating your _bindProps
definition to:
_bindProps(obj) {
Object.keys(obj).forEach(k => obj[k] = obj[k].bind(this));
return obj;
}
并且用一个对象调用它的做法是:
And calling it with an object does the trick:
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
返回。
You could tidy the above up a little but that does now do the right thing and if you call this.props.foo()
in the child component you will get Jack
returned back.
我有兴趣知道你为什么这样做吗?这不是我通常不得不在任何时候做的。
I'd be interested to know why you're doing this though? This isn't something I've typically had to do at any point.
这篇关于可重新启用的基数与ES6的反应组件绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!