小编典典

React-将类添加到子组件

reactjs

即时通讯使用react和我有一个组件,只需要呈现孩子并根据条件将它们添加一个类。最好的方法是什么?


阅读 323

收藏
2020-07-22

共1个答案

小编典典

我一周前就弄清楚了,这就是我想要的:

export default class ContainerComponent extends React.Component {
    constructor(props) {
        super(props);

        this.modifyChildren = this.modifyChildren.bind(this);
    }

    modifyChildren(child) {
        const className = classNames(
            child.props.className,
            {...otherClassses}
        );

        const props = {
            className
        };

        return React.cloneElement(child, props);
    }
    render() {
        return (<div>
            {React.Children.map(this.props.children, child => this.modifyChildren(child))}
        </div>);
    }
}
2020-07-22