如何创建一个包装器来更改组件的道具

how to create a wrapper that changes the props for the component in react

我第一次尝试使用 React 组件做一些事情,需要你的帮助, 我想动态地将一个组件包装在另一个组件中并更改其道具。 例如,假设我有这个组件:

假设我想从包装器

传递key3

注意:将 React-Native 与 TypeScript 结合使用

type Props { key1: string, key2: string, key3: any }
const FirstComponent = ({ key1, key2, key3 }:Props) => {
   return <View>
    <Text>{key1} and {key2} with {key3}</Text>
<View/>
}

包装示例

const FirstComponentWrapper = (props:Props) => {
 const value = 'something';
  return <FirstComponent {...props} key3={value} />
}

这里的包装器让组件可以访问 key3 值。 如果我有一个包含很多组件的大型应用程序并且我无法每次都创建它,所以我正在寻找一种方法来在某处创建包装器以便我可以轻松调用它。

示例:

type Props = {
  component: React.ReactNode // not just function component it can be also class 
                             // component ;
  newValue: any;
}
export const Wrapper = ({ component, newValue }:Props) => {
  // this is what I missed
  // looking to return any passed component here as in the example I mentioned with new 
  // value that's added to the prop
}

有什么帮助吗?提前致谢。

您可以在 Props 中使用 children 来使用 Wrapper 组件渲染包装组件

type Props = {
  children: React.ReactNode 
  newValue: any;
}
export const Wrapper = ({ children, newValue, ...otherProps }: Props) => {
  return React.cloneElement(children, {...otherProps, key3: newValue})
}

用法

<Wrapper newValue="value3">
  <FirstComponent key1="value1" key2="value2" />
</Wrapper>

另一种方式,你可以有一个 higher-order component (HOC) 在你的包装组件被渲染之前修改你的道具

const withModifiedProps = (WrappedComponent: React.ReactNode) => {
   const Wrapper = ({ newValue, ...props }) => {
      return <WrappedComponent {...props} key3={newValue} />
   }
   return Wrapper
}

之后,你可以用 HOC 包装你的组件

export default withModifiedProps(FirstComponent)

只要可以 FirstComponent,您就可以将 newValue 传递给它,它会自动填充 key3 作为 newValue

的替代品
<FirstComponent key1="value1" key2="value2" newValue="value3" />