2017-02-28 44 views
0

我想从React.props.children呈现单个项目。从React.children渲染单个项目 - 如何?

我的用法是这样的......

render() { 
    return (
     <DataListManager idName = "stops" 
         baseUrl={`/api/stop/${HiddenState.getAltId()}`} 
         errorProcessor={new ErrorProcessor()} 
         emptyMessage = "No stops have been added to this service yet." 
         confirmDeleteTitleCallback={(stop) => `Delete ${stop.name}?`} 
         confirmDeleteMessageCallback={(stop) => `Do you want to delete the stop ${stop.name}? This cannot be undone.`}> 
      <StopForm for="create" 
         formId="new-stop" 
         submitText="Add stop" /> 
      <StopForm for="edit" 
         submitText="Update stop" /> 
     </DataListManager> 
    ); 
} 

我有2个“StopForm”成分,但我只是想使它们的1依赖于组件的状态 - 孩子们传下来的一对于创建和编辑场景都是通用的切换组件都有几层。我想为不同的场景呈现不同的表单。

下面是创建一个新的项目时呈现编辑视图的方法...

renderEdit(object, onCancelClickCallback, onSubmitSuccessCallback) { 
    const childrenWithProps = React.Children.map(this.props.children, (child) => React.cloneElement(child, { 
     stop: object, 
     onChange: this.onChange, 
     onSubmit: this.onSubmit, 
     onCancel: onCancelClickCallback, 
     onSubmitSuccess: onSubmitSuccessCallback 
    })); 

    childrenWithProps.forEach((child) => { 
     if (child.props.for == "create") { 
      return child; 
     } 
    }); 
} 

(渲染()方法将调用要么renderEdit()或renderDisplay()依赖于它的状态)。

但是,我似乎无法得到一个单一的项目,但是。我曾尝试以下变化,但没有工作过......

childrenWithProps.forEach((child) => { 
     if (child.props.for == "create") { 
      return <div>{child}</div>; 
     } 
    }); 

    childrenWithProps.forEach((child) => { 
     if (child.props.for == "create") { 
      return {child}; 
     } 
    }); 

孩子似乎是一个有效的物体做出反应,但我一直看到这个错误...

渲染():有效作出反应元素(或null)必须被返回。您可能返回了未定义的数组或其他无效对象。

+0

'forEach'不返回任何内容。 – azium

+0

为什么你需要把它们当作孩子来传递,而不是将它们渲染到你的逻辑所在的位置? – ericgio

+0

它们将呈现在表单组件特殊性(它们可以编辑的数据类型以及用于这样做的字段)的地方,因为数据列表的主要功能是通用的,所以它们不会被知道。 –

回答

1

您不应该在第一时间返回forEach。使用filtermap来做你需要的东西。

const result = childrenWithProps.filter((child) => { 
    return (child.props && child.props.for === "create"); 
} 
return result[0] || null; 
+0

同意 - 我的不好。 –

0

我设法使用Array.prototype.filter这个工作到底如下...

renderEdit(object, onCancelClickCallback, onSubmitSuccessCallback) { 
    const childrenWithProps = React.Children.map(this.props.children, (child) => 
     React.cloneElement(child, { 
      stop: object, 
      onChange: this.onChange, 
      onSubmit: this.onSubmit, 
      onCancel: onCancelClickCallback, 
      onSubmitSuccess: onSubmitSuccessCallback 
     }) 
    ); 

    return <div>{childrenWithProps.filter((child) => child.props.for == "create")}</div>; 
} 

所以我就在这一个项目的数组。虽然这看起来有些轻率 - 更好的答案欢迎!