[英]How to render a child component within parent component using react and typescript?
i want to conditionally render a child component within parent component using react and typescript.我想使用 react 和 typescript 有条件地渲染父组件中的子组件。
below is my code,下面是我的代码,
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>
</>
);
}
the above code gives me error like below上面的代码给了我如下错误
Warning: Functions are not valid as a React child.警告:函数作为 React 子级无效。 This may happen if you return a Component instead of from render.
如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。 Or maybe you meant to call this function rather than return it.
或者,也许您打算调用此 function 而不是返回它。
could someone help me fix this.有人可以帮我解决这个问题。 thanks.
谢谢。 i am new to using react and typescript.
我是使用 react 和 typescript 的新手。
Return statement of a react component only accept one jsx so you need to wrap your components react 组件的 return 语句只接受一个 jsx,所以你需要包装你的组件
return (
<>
{isChecked && <ChildComponent />}
<SomeotherComponent>//some jsx</SomeOtherComponent>
</>
);
try this:尝试这个:
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.