组件只能有一个根元素,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) => {
...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…