[英]Typescipt :typing the props passed by a wrapper component in React
我有一个包装组件 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})
</>
)
};
现在我想将它与需要这样的someState:string
道具的组件 X 一起使用
<A fooProp="foobar">
<X/>
</A
但是 Typescript 抱怨 X 没有提供所需的 someState 道具; 我如何让他知道组件 A 能够将someState
道具传递给它的孩子?
只需将道具声明为可选:
interface XProps {
someState?: string;
}
class X extends React.Component<XProps> { ... }
也许更好的方法是 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.