简体   繁体   English

Typescipt:在 React 中键入包装器组件传递的道具

[英]Typescipt :typing the props passed by a wrapper component in React

I have a wrapper component A which is able to add props to children like this我有一个包装组件 A,它能够像这样向孩子添加道具

interface AProps {
   fooProp: string
}

const A : FunctionComponent<AProps> = (props)=>{
   const [someState, setSomeState] = useState("");//local state i want to pass to children
   const {children} = props;

   //...some other code setting someState

   // type guard making the compiler happy
   if (!React.isValidElement(children){
      return <></>
   }

   return (
     <>
         React.cloneElement(React.Children.only(children, {someState})
     </>
   )
};

Now i want to use it with a component X which needs a someState:string prop like this现在我想将它与需要这样的someState:string道具的组件 X 一起使用


<A fooProp="foobar">
   <X/>
</A

But Typescript is complaining that X is not provided with required someState prop;但是 Typescript 抱怨 X 没有提供所需的 someState 道具; How do i make him aware that component A is able to pass the someState prop to its children?我如何让他知道组件 A 能够将someState道具传递给它的孩子?

Just declare the prop as optional:只需将道具声明为可选:

    interface XProps {
        someState?: string;
    }

    class X extends React.Component<XProps> { ... }

EDIT编辑

Maybe a better approach is HOC (High Order Component), with no need for React.cloneElement也许更好的方法是 HOC(高阶组件),不需要React.cloneElement

interface AProps {
   fooProp: string
}
interface XProps {
   someState: string;
}

function withSomeState(X: React.Component<XProps>) {
    const A: FunctionComponent<AProps> = (props) => {
       const [someState, setSomeState] = useState("");//local state i want to pass to children

       //...some other code setting someState

       // type guard making the compiler happy
       if (!React.isValidElement(X){
          return <></>
       }

       return (
         <X {someState} />
       );
    }
    return A;
}
const A = withSomeState(X);

<A fooProp="foobar" />

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

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