【问题标题】:Rendering a component as the parent of the actual component将组件渲染为实际组件的父级
【发布时间】:2019-12-11 11:48:58
【问题描述】:

我有 2 个组件,我希望第一个组件成为第二个组件中的渲染道具,如果它被定义,它将封装第二个组件的内容。我不太明白如何写这个,而且我在渲染道具上找到的文档往往难以理解。有没有人写过类似的实现?

我追求的一般想法是,您将component1 的道具传递给component1 道具为component2,它会渲染<Component1> 及其在component2 中的道具。

我正在尝试做的粗略代码示例(它并不意味着工作)

    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>);

    }

编辑:更改了示例,因为意图令人困惑。

编辑:现在只会将第一个组件作为道具传递给第二个组件。我认为一般的答案是不要尝试将一个组件用作两个组件,而只是坚持使用子组件。

【问题讨论】:

  • 没有意义 - 您将组件作为道具传递,但是您正在渲染导入的组件,而不是传递下来的组件。
  • 您的意图到底是什么?描述你想要实现的目标
  • 已更新,目的是能够从组件 2 内部渲染一个实例组件 1,其中 props 作为组件 2 的父组件。

标签: reactjs typescript


【解决方案1】:

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

无论如何 - 你为什么要将整个组件作为道具传递,即使你基本上可以导入它?

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

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>);
}

【讨论】:

  • 我的例子可能有点模糊,这是因为我需要第一个组件来包装第二个组件,但我还需要能够在渲染第二个组件时将属性传递给第一个组件。考虑一个可选的 fieldset 组件,它有一些单选按钮作为它的子项。
  • @user3062123 然后使用几个标志来确定是否应该在 Component2 中渲染一些额外的内容,我个人会避免将整个组件作为道具传递。
猜你喜欢
  • 1970-01-01
  • 2023-04-09
  • 2021-12-01
  • 2019-06-20
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 2019-06-01
  • 1970-01-01
相关资源
最近更新 更多