首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将组件呈现为实际组件的父组件。

将组件呈现为实际组件的父组件。
EN

Stack Overflow用户
提问于 2019-12-11 11:48:58
回答 1查看 42关注 0票数 0

我有两个组件,我希望第一个组件是第二个组件中的呈现支柱,如果定义了第二个组件,它将封装第二个组件的内容。我不太明白如何写这个,我在渲染道具上找到的文档往往很难理解。有没有人写过类似的实现?

我想要的一般想法是,您可以在component1component1道具中传递component2的道具,并在component2中使用它的道具来呈现<Component1>

粗略代码示例,说明我正在尝试做什么(这不是要工作的)

代码语言:javascript
复制
    interface Component1 {
     id?: string;
     children: React.ReactNode;
    }

    const Component1 = (props: Component1) => {
      const { children } = props;
      return (<div className="component1">{children}</div>)
    }

    interface Component2 {
      component1?: (propsForComponent1) => <Component1 {...propsForComponent1}>
    }

    const Component2 = (props: Component2) => {
      const {component1} = props;
      if (component1) {
        return {component1({id: 'exampleId', children: <div className="component2">Stuff for component 2</div>)}}
      };
      return (<div className="component2">Stuff for component 2</div>);

    }

编辑:已经改变了例子,因为意图是混淆人们。

编辑:现在将第一个组件作为支柱传递到第二个组件中。我认为一般的答案是不要尝试将组件作为两个组件使用,而只是将其应用于儿童。

EN

回答 1

Stack Overflow用户

发布于 2019-12-11 11:58:51

在代码示例中实际发生的情况是,即使您将整个组件(Component1)作为支柱传递,您也是而不是呈现它,而是使用导入的(或在范围内可访问的) Component1

无论如何,你为什么要把一个完整的组件传递下来作为一个支柱,即使你基本上可以导入它呢?

我的建议是-使用一个道具,而不是一个组件,而是一个布尔标志,它决定组件是否应该被包装。

代码语言:javascript
复制
interface Component2 {
  shouldBeWrapped?: boolean;
}

const Component2 = ({ shouldBeWrapped }: Component2) => {
  if (shouldBeWrapped) {
    return (
       <Component1 with props given in on component1 property>
          <div className="component2">Stuff for component 2</div>
       </Component1>
    );
  }

  return (<div className="component2">Stuff for component 2</div>);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59285154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档