[英]How to render a child component within parent component using react and typescript?
我想使用 react 和 typescript 有条件地渲染父组件中的子组件。
下面是我的代码,
const Parent = ({ prop1, prop2 }: { prop1: Prop1, prop2: Prop2;}) => {
const isChecked = true;
return (
{isChecked && <ChildComponent />}
<SomeotherComponent>
//some jsx
</SomeOtherComponent>
);
}
const ChildComponent = () => {
return (
<>
<div>something</div>
<div>something</div>
</>
);
}
上面的代码给了我如下错误
警告:函数作为 React 子级无效。 如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。 或者,也许您打算调用此 function 而不是返回它。
有人可以帮我解决这个问题。 谢谢。 我是使用 react 和 typescript 的新手。
react 组件的 return 语句只接受一个 jsx,所以你需要包装你的组件
return (
<>
{isChecked && <ChildComponent />}
<SomeotherComponent>//some jsx</SomeOtherComponent>
</>
);
尝试这个:
const Parent = ({ prop1, prop2 }: { prop1: Prop1, prop2: Prop2;}) => {
const isChecked = true;
return (
<>
{isChecked && <ChildComponent />}
<SomeotherComponent>
//some jsx
</SomeOtherComponent>
</>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.