简体   繁体   English

如何使用 react 和 typescript 在父组件中渲染子组件?

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

相关问题 在父组件内有条件地渲染子组件 - Conditionally Render Child Component within Parent Component 如何从一个子组件在父组件中设置 state 并使用 react 和 typescript 在另一个子组件中访问 state? - How to set state in parent from one child component and access the state in another child component using react and typescript? 反应原生中呈现子组件而不是父组件 - Render child component and not parent component in react native 在React中单击子组件时如何呈现父组件? - How to render a parent component upon clicking a child component in React? 反应:如何从子组件渲染父组件? - React: How to render a parent component from child component? 如何从父组件调用 React/Typescript 子组件 function? - How to call React/Typescript child component function from parent component? 如何使用 react、typescript 和 styled-component 将 onclick 方法从父组件传递给子组件? - How to pass onclick method to child component from parent using react, typescript, and styled-component? React JS:在父组件内调用子组件方法(与打字稿反应) - React JS : Calling Child component method within parent component (React with typescript) 如何将数组作为道具传递并在 typescript 反应钩子中的子组件中渲染 - How to pass an array as a prop and render in child component in typescript react hooks React-Native子组件不会在父组件内呈现信息 - React-Native the child component don't render the information within the parent component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM