gpt4 book ai didi

javascript - 从 React.children 渲染单个项目 - 如何?

转载 作者:行者123 更新时间:2023-12-03 04:54:02 25 4
gpt4 key购买 nike

我正在尝试从 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 个组件 - 子组件会向下传递几层到切换组件,该组件对于创建和编辑场景都是通用的。我想针对不同的场景呈现不同的形式。

这是创建新项目时呈现编辑 View 的方法...

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)。您可能返回了未定义的数组或其他无效对象。

最佳答案

您首先不应该在 forEach 中返回。使用 filtermap 来做你需要的事情。

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

关于javascript - 从 React.children 渲染单个项目 - 如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42516259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com