无法从 React.Children.map() 访问 this.state



正如标题所说,我需要访问所有子级map函数的每个child元素,React.Children.map(this.props.children, (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  
      })
    })
  }

你是对的,你需要将map包装在renderChildrenreturn ( ... )中。

当您执行此操作时return(<div>{this.renderChildren(callbacks)}</div>)如果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

我想通了。首先,必须在此处使用 npm 安装将transform-class-properties添加到我的.babelrc文件中

然后,我像上面建议的那样使用箭头函数自动绑定它,但我仍然无法从 .map 函数内部访问我的状态。我最终发现了这个 Github 问题,在这里

也就是说,将函数与地图函数中的第二个参数绑定,我这样做了,但它不起作用。这是修订版...

 renderChildren = (funcs) => {
    return (
      React.Children.map(this.props.children, (child) => {
        return React.cloneElement(child, {
          state: this.state, 
          callbackFuncs: funcs
        })
      }, this)
    )
  };