React设计权限控制时通过cloneElement修改元素的props属性

Posted jimaww

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React设计权限控制时通过cloneElement修改元素的props属性相关的知识,希望对你有一定的参考价值。

部分简化后的代码如下:

interface Iprops {
    roles: string;
}

export class Authorize extends React.Component<Iprops, any>{
    renderDom() {
        const { roles, children } = this.props;
        if (authorize(roles) === true) {
            return this.props.children;
        } else if (authorize(roles) === ‘disable‘) {
            return Children.map(children, (child: any) => cloneElement(child, { disabled: true }));
        } else {
            return null;
        }
    }

    render(): any {
        return this.renderDom();
    }
}

注意:设置disabled属性需要子组件对props中的disabled有处理,否则也是无效的,如:可用material-ui的button组件作为子组件测试。

关于 cloneElement https://zh-hans.reactjs.org/docs/react-api.html#cloneelement

以上是关于React设计权限控制时通过cloneElement修改元素的props属性的主要内容,如果未能解决你的问题,请参考以下文章