部分簡化后的代碼如下:
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
