简体   繁体   English

如何根据 React + Typescript 中的类型将道具传递给孩子

[英]How to pass props to children according to type in React + Typescript

Apologies if this has been answered elsewhere, it seems like a basic problem but I wasn't able to find an answer anywhere.抱歉,如果这已在其他地方得到解答,这似乎是一个基本问题,但我无法在任何地方找到答案。

I am trying to find a way to conditionally pass props to children components based on the the type (ie component type) of the child.我试图找到一种方法,根据子组件的类型(即组件类型)有条件地将道具传递给子组件。

For instance given a generic functional component例如给定一个通用功能组件

const Parent = ({propA, propB, children, ...props}) => (
    <div {...props}>
        {children}
    </div>
)

in which I expect to receive only A and B components as children.我希望只收到AB组件作为孩子。 I want propA to be passed only to children of type A and propB to be passed only to children of type B such that我希望propA只传递给A类型的孩子,而propB只传递给B类型的孩子,这样

const Parent = ({propA, propB, children, ...props}) => (
  <div {...props}>
      {React.Children.map<React.ReactNode, React.ReactNode>(children, child => {
        if (React.isValidElement(child)) {
          if (/* child if of type A */)
            return React.cloneElement(child, { propA })
          if (/* child if of type B */)
            return React.cloneElement(child, { propB })
        }
      })}
  </div>

if you know the mapping between Component and its respective props, you can create an array of objects and then map over it, while passing it from the parent.如果您知道 Component 与其各自的 props 之间的映射,则可以创建一个对象数组,然后在其上创建 map,同时从父级传递它。 Example例子

//calling of parent
<Parent renderObject = {[
  {prop : propA, comp: compA},
  {prop : propB, comp: compB}
 ]}
 ...restOfTheProps
/>

Now you can actually code something like this using map现在您实际上可以使用 map 编写类似这样的代码

const Parent = ({ renderObject, ...props}) => (
  <div {...props}>
      {renderObject.map((renderObj)=>{
          return <renderObj.comp {...renderObj.prop} />
       })}
  </div>
)

instead of using children, you can pass component as props.您可以将组件作为道具传递,而不是使用孩子。

You can use child.type您可以使用 child.type

const Parent = ({propA, propB, children, ...props}) => (
  <div {...props}>
      {React.Children.map<React.ReactNode, React.ReactNode>(children, child => {
          if (React.isValidElement(child)) {
              if (child.type===A) {
                  return React.cloneElement(child, { propA })
              } else {
              return React.cloneElement(child, { propB })
              }
          }
      })}
   </div>)

same this you can do it!同样的,你可以做到!

<Modal isActive={true} > 
  <h1>Modal here!</h1>
</Modal>

and in Your component do same this:并在您的组件中执行相同操作:

type Props ={
  children: React.ReactNode;
  isActive: boolean;
}

const Modal:React.FC<Props> = ({children, isActive}) => {
  return isActive && children;
}
export default Modal;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM