【问题标题】:Can't access this.state from React.Children.map()无法从 React.Children.map() 访问 this.state
【发布时间】:2018-03-20 00:01:35
【问题描述】:

正如标题所说,我需要访问所有孩子的地图功能的每个child元素,React.Children.map(this.props.children, (child)...

我需要这个,因为我想有条件地渲染某些道具,并且还根据当前正在渲染的孩子阻止基于某些条件的渲染。

我已经在构造函数中绑定了这个函数

this.renderChildren = this.renderChildren.bind(this);

但它仍然无法正常工作。 我什至可以让这个 map 函数工作的唯一方法是将它包装在 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  
      })
    })
  }

【问题讨论】:

    标签: reactjs this state children


    【解决方案1】:

    您是对的,您需要将map 包装在return ( ... ) 中的renderChildren 中。

    当您这样做时,return(&lt;div&gt;{this.renderChildren(callbacks)}&lt;/div&gt;) 如果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

    【讨论】:

    • 我最初在运行箭头函数时遇到问题,但将transform-class-properties 添加到 babel 并且它正在运行。但是,我仍然无法访问this.state。我很困惑。
    【解决方案2】:

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

    然后,我像上面建议的那样使用箭头函数自动绑定它,但我仍然无法从 .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)
        )
      };
    

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 2018-07-17
      • 2020-08-18
      • 2018-02-19
      • 2017-01-06
      相关资源
      最近更新 更多