[英]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.