Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

react用typescript返回cloneElement时的类型问题

代码如下

interface Props {
    role: string,
    children: ReactChild
}
const HasRole: React.FC<Props> = ({role, children, ...props}) => {
    const roles = useSelector(state => state.roles);
    if (roles.includes(role)) {
        return Children.map(children, child => {
            if (isValidElement(child)) {
                return cloneElement(child, props);
            }
            return child;
        })
    } else {
        return null;
    }
}

这是报错

image.png

所以,HasRole 的类型究竟应该怎么写?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

组件只能有一个根元素,Children.map返回了数组,如果定义为组件的话稍微改下就可以了:

interface Props {
    role: string,
    children: ReactChild
}
const HasRole: React.FC<Props> = ({role, children, ...props}) => {
    const roles = useSelector(state => state.roles);
    if (roles.includes(role)) {
        return (
            <>
                {
                    Children.map(children, child => {
                        if (isValidElement(child)) {
                            return cloneElement(child, props);
                        }
                        return child;
                    })
                }
            </>
        )
    } else {
        return null;
    }
}

或者不做组件使用,只当作普通的渲染方法:

interface Props {
    role: string,
    children: ReactChild
}
const HasRole: React.ReactNode = ({role, children, ...props}: Props) => {
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...