How to assign the correct typing to React.cloneElement when giving properties to children?

后端 未结 1 964
轻奢々
轻奢々 2020-12-05 06:13

I am using React and Typescript. I have a react component that acts as a wrapper, and I wish to copy its properties to its children. I am following React\'s guide to using c

相关标签:
1条回答
  • 2020-12-05 06:47

    The problem is that the definition for ReactChild is this:

    type ReactText = string | number;
    type ReactChild = ReactElement<any> | ReactText;
    

    If you're sure that child is always a ReactElement then cast it:

    return React.cloneElement(child as React.ReactElement<any>, {
        width: this.props.width,
        height: this.props.height
    });
    

    Otherwise use the isValidElement type guard:

    if (React.isValidElement(child)) {
        return React.cloneElement(child, {
            width: this.props.width,
            height: this.props.height
        });
    }
    

    (I haven't used it before, but according to the definition file it's there)

    0 讨论(0)
提交回复
热议问题