React - 向子组件添加类 [英] React - adding class to children components
本文介绍了React - 向子组件添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 react 并且我有一个组件,它只需要渲染子项并根据条件为它们添加一个类.最好的方法是什么?
解决方案
我一周前就想通了,这就是我想要的:
export default class ContainerComponent extends React.Component {构造函数(道具){超级(道具);this.modifyChildren = this.modifyChildren.bind(this);}修改孩子(孩子){const 类名 = 类名(child.props.className,{...其他类});const 道具 = {班级名称};返回 React.cloneElement(child, props);}使成为() {返回 (<div>{React.Children.map(this.props.children, child => this.modifyChildren(child))}
);}}
im using react and I have a component that simply needs to render the children and add them a class according to a condition. Whats the best way of doing it?
解决方案
I figured it out a week ago, this is what I wanted :
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>);
}
}
这篇关于React - 向子组件添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文