Reactjs 如何使用react和typescript在父组件中呈现子组件?
我想使用react和typescript有条件地呈现父组件中的子组件 下面是我的代码Reactjs 如何使用react和typescript在父组件中呈现子组件?,reactjs,typescript,Reactjs,Typescript,我想使用react和typescript有条件地呈现父组件中的子组件 下面是我的代码 const Parent = ({ prop1, prop2 }: { prop1: Prop1, prop2: Prop2;}) => { const isChecked = true; return ( {isChecked && <ChildComponent />} <SomeotherComponent>
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>
</>
);
}
const Parent=({prop1,prop2}:{prop1:prop1,prop2:prop2;})=>{
const isChecked=true;
返回(
{isChecked&}
//一些jsx
);
}
常量ChildComponent=()=>{
返回(
某物
某物
);
}
上面的代码给出了如下错误
警告:函数作为子函数无效。如果返回组件而不是从渲染返回组件,则可能会发生这种情况。或者你是想调用这个函数而不是返回它
有人能帮我修一下吗。谢谢我不熟悉使用react和typescript。react组件的Return语句只接受一个jsx,因此需要包装组件
return (
<>
{isChecked && <ChildComponent />}
<SomeotherComponent>//some jsx</SomeOtherComponent>
</>
);
返回(
{isChecked&}
//一些jsx
);
试试这个:
const Parent = ({ prop1, prop2 }: { prop1: Prop1, prop2: Prop2;}) => {
const isChecked = true;
return (
<>
{isChecked && <ChildComponent />}
<SomeotherComponent>
//some jsx
</SomeOtherComponent>
</>
);
}
const Parent=({prop1,prop2}:{prop1:prop1,prop2:prop2;})=>{
const isChecked=true;
返回(
{isChecked&}
//一些jsx
);
}
您的父组件
和子组件
都在同一个文件中?子组件在不同的文件中如果答案有帮助,请尝试投赞成票:)@TaghiKhavari:可以研究一下这个问题吗