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