我正在尝试从React.props.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;
}
});
}
(render()方法将根据其状态调用renderEdit()或renderDisplay()。
我似乎无法渲染单个项目。我尝试了以下变化,但没有一个有效...
childrenWithProps.forEach((child) => {
if (child.props.for == "create") {
return <div>{child}</div>;
}
});
childrenWithProps.forEach((child) => {
if (child.props.for == "create") {
return {child};
}
});
Child似乎是一个有效的React对象,但我一直看到这个错误...
render():必须返回有效的React元素(或null)。您可能已经返回了undefined,数组或其他一些无效对象。
答案 0 :(得分:1)
您不应该首先返回forEach
。使用filter
或map
来完成您需要的操作。
const result = childrenWithProps.filter((child) => {
return (child.props && child.props.for === "create");
}
return result[0] || null;
答案 1 :(得分: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>;
}
所以我得到了一个包含单个项目的数组。这看起来有点不合时宜 - 欢迎更好的答案!
答案 2 :(得分:0)
类实例方法:
render
组件render() {
const children = this.props.children;
return <div>{children && this.getChildComponents(children)}</div>;
}
功能:
struct Response<ResultType> : Decodable where ResultType : Decodable {
let results: ResultType
let status: Int
}