React Native 将一个组件插入到另一个组件中

时间:2021-01-22 19:38:08

标签: react-native

有没有办法在特定位置将一个 RN 组件“注入”到另一个组件中。 假设我有这个组件:

const Original = () => {
  return (
    <View>
      <Text>Hello</Text>
      {InsertChildComponentHere}
    </View>
  )
}

const ChildComponent = () => {
  return (
    <View>
      <Text>I am a child component</Text>
    </View>
  )
}

1 个答案:

答案 0 :(得分:1)

要将组件注入其他组件 (HOC),您的组件必须接受“组件”作为参数。你可以这样写:

const Original = (Component) => {
  const newComponent = ({ ...props }) => {
    return (
      <Fragment>
        <Text>Hello</Text>
        <Component {...props} />
      </Fragment>
    );
  };

  return newComponent;
};

要创建您可以编写的 HOC:

const MyComponent = withOriginal(ChildComponent);