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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM