首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法从React.Children.map()访问this.state

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

Stack Overflow用户
提问于 2018-03-20 08:01:35
回答 2查看 572关注 0票数 0

正如标题所说,我需要访问所有子对象React.Children.map(this.props.children, (child)...的映射函数的每个child元素

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

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

代码语言:javascript
复制
this.renderChildren = this.renderChildren.bind(this);

但它仍然不起作用。让这个映射函数工作的唯一方法就是把它包装在一个return()函数中。有什么想法吗?

代码语言:javascript
复制
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>)

以下代码将不起作用(不包含在返回中)

代码语言:javascript
复制
renderChildren(funcs) {
    React.Children.map(this.props.children, (child) => {
      return React.cloneElement(child, {
        state: this.state,    
        callbackFuncs: funcs  
      })
    })
  }
EN

回答 2

Stack Overflow用户

发布于 2018-03-20 08:19:32

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

执行此操作时,如果renderChildren(callbacks)未返回任何内容,则{this.renderChildren(callbacks)}将为空。

来解决您的问题,而不是在构造函数中绑定this

在构造函数中删除此行this.renderChildren = this.renderChildren.bind(this);

变化

代码语言:javascript
复制
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
    })
  })
)
}

至

代码语言:javascript
复制
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

票数 0
EN

Stack Overflow用户

发布于 2018-03-20 20:01:56

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

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

也就是说,将函数与map函数中的第二个arg绑定在一起,我这样做了,但它不起作用。这是修改后的版本。

代码语言:javascript
复制
 renderChildren = (funcs) => {
    return (
      React.Children.map(this.props.children, (child) => {
        return React.cloneElement(child, {
          state: this.state, 
          callbackFuncs: funcs
        })
      }, this)
    )
  };
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49374330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档