【问题标题】:How to render a child component within parent component using react and typescript?如何使用 react 和 typescript 在父组件中渲染子组件?
【发布时间】:2021-04-24 14:31:16
【问题描述】:

我想使用 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 子级无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者,也许您打算调用这个函数而不是返回它。

谁能帮我解决这个问题。谢谢。我是使用 react 和 typescript 的新手。

【问题讨论】:

  • 您的parentchild 组件都在同一个文件中?
  • 孩子在不同的文件中
  • 如果答案有帮助,请尝试给它一个 upVote :)
  • @TaghiKhavari: 可以看看这个问题stackoverflow.com/questions/65818598/…

标签: reactjs typescript


【解决方案1】:

return 组件的return 语句只接受一个jsx,所以你需要包装你的组件

return (
  <>
    {isChecked && <ChildComponent />}
    <SomeotherComponent>//some jsx</SomeOtherComponent>
  </>
);

【讨论】:

    【解决方案2】:

    试试这个:

    const Parent = ({ prop1, prop2 }: { prop1: Prop1, prop2: Prop2;}) => {
      const isChecked = true;
      return (
        <>
          {isChecked && <ChildComponent />}
          <SomeotherComponent>
          //some jsx
          </SomeOtherComponent>
        </>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-23
      • 2018-11-12
      • 2020-10-15
      • 2018-11-06
      • 1970-01-01
      • 2022-07-04
      • 2019-10-07
      • 2021-10-23
      相关资源
      最近更新 更多