正如标题所说,我需要访问所有子对象React.Children.map(this.props.children, (child)...的映射函数的每个child元素
我需要这个,因为我想要有条件地渲染某些道具,并根据当前正在渲染的子对象来阻止基于某些条件的渲染。
我已经在构造函数中绑定了这个函数
this.renderChildren = this.renderChildren.bind(this);但它仍然不起作用。让这个映射函数工作的唯一方法就是把它包装在一个return()函数中。有什么想法吗?
renderChildren(funcs) {
// debugger
return (
React.Children.map(this.props.children, (child) => {
debugger // *** Need to access `this.state` from in here ***
return React.cloneElement(child, {
state: this.state, // *** Need access here too
callbackFuncs: funcs
})
})
)
}
...
return(<div>{this.renderChildren(callbacks)}</div>)以下代码将不起作用(不包含在返回中)
renderChildren(funcs) {
React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, {
state: this.state,
callbackFuncs: funcs
})
})
}发布于 2018-03-20 08:19:32
您是对的,您需要将map包装在renderChildren中的return ( ... )中。
执行此操作时,如果renderChildren(callbacks)未返回任何内容,则{this.renderChildren(callbacks)}将为空。
来解决您的问题,而不是在构造函数中绑定this
在构造函数中删除此行this.renderChildren = this.renderChildren.bind(this);
变化
renderChildren(funcs) {
// debugger
return (
React.Children.map(this.props.children, (child) => {
debugger // *** Need to access `this.state` from in here ***
return React.cloneElement(child, {
state: this.state, // *** Need access here too
callbackFuncs: funcs
})
})
)
}至
renderChildren = (funcs) => {
// debugger
return (
React.Children.map(this.props.children, (child) => {
debugger // *** Need to access `this.state` from in here ***
return React.cloneElement(child, {
state: this.state, // *** Need access here too
callbackFuncs: funcs
})
})
)
}然后,您可以在闭包中随意访问this
发布于 2018-03-20 20:01:56
我想通了。首先,必须使用npm install以及here将transform-class-properties添加到我的.babelrc文件中
然后,我像上面建议的那样用箭头函数自动绑定了它,但我仍然无法从.map函数内部访问我的状态。我最终找到了这个Github问题,Here
也就是说,将函数与map函数中的第二个arg绑定在一起,我这样做了,但它不起作用。这是修改后的版本。
renderChildren = (funcs) => {
return (
React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, {
state: this.state,
callbackFuncs: funcs
})
}, this)
)
};https://stackoverflow.com/questions/49374330
复制相似问题