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