javascript - 从 React.Children 获取返回变量

标签 javascript reactjs

我已经尝试让它工作一段时间了,但我不确定我做错了什么。我的表单组件有包含常规 html 标记和输入的子组件。如果 child 是输入,我想添加 AttachToForm 和 detachFromForm 函数。如果它不是输入,我想继续遍历子元素以确保该元素没有子输入字段。

问题是无论我做什么,即使使用虚拟数据,我也无法让 traverseChildren 返回任何内容。我不确定我是否不理解基本的 JS 或 React.children

registerInputs(children) {

    React.Children.forEach(children, function(child) {
      if (child.props && child.props.name) {
        this.newChildren.push(React.cloneElement(child, {
            detachFromForm: this.detachFromForm,
            attachToForm: this.attachToForm,
            key: child.props.name
        }))
      } else if (child.props && child.props.children){
        var traverseChildren  = this.traverseChildren(child.props.children, child);
        //this.newChildren.push(traverseChildren);
        console.log(traverseChildren) //=> undefined
      }
    }.bind(this));
    console.log(this.newChildren) // =>[]
 }

traverseChildren(children, current){
    var current = current;
    var me = React.Children.forEach(children, function(child) {
      if (child.props && child.props.name) {
         return React.cloneElement(child, {
            detachFromForm: this.detachFromForm,
            attachToForm: this.attachToForm,
            key: child.props.name
          });
      } else if (child.props && child.props.children){
          return "hello";//this.traverseChildren(child.props.children, current);
      } else {
          return current;
      }
   });
   console.log(me) // => undefined
}

最佳答案

React.Children.forEach不返回值。它对数组中的每个项目执行一次您提供的函数。试试这个:

traverseChildren(children, current){
    var current = current;
    React.Children.forEach(children, function(child) {
      if (child.props && child.props.name) {
         return React.cloneElement(child, {
            detachFromForm: this.detachFromForm,
            attachToForm: this.attachToForm,
            key: child.props.name
          });
      } else if (child.props && child.props.children){
          this.traverseChildren(child.props.children, current);
      } else {
          console.log(current);
      }
   });
}

或者,也许您正在寻找 React.Children.map .

关于javascript - 从 React.Children 获取返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33702206/

相关文章:

javascript - 如何在每个时间段检测到最大条目时更改日历覆盖

javascript - 如何防止用户通过 PHP 而不是 jQuery 在输入框中键入特殊字符?

javascript - Recaptcha 弹出警告

javascript - 如何从数组中的名称调用对象

javascript - 如何将修改后的 prop 发送到 redux store?

javascript - 如何在javascript中验证手机号码?

javascript - 未捕获类型错误 : Cannot set property 'onclick' of null. 尝试了 window.onload

javascript - 在 JavaScript 中初始化对象中的空数组

javascript - 使用 React 处理大表单

Reactjs不加载文本字体