React 中怎么操作虚拟DOM 的Class属性?
React 中怎么操作虚拟DOM 的Class属性
sanyuelanv
#2
<div className = {this.state.className} ></div>
<div className = {this.props.className} ></div>
Ad007
#3
render() {
this.debug('render ....');
this.components.push(<AttentionScreen ref="attention" message={this.state.message} />);
this.components.forEach(function(component, index) {
if(index > 0 && !component.classList.contains('hidden')) {
component.classList.add('hidden');
}
}, this);
return (<div> { this.components } </div>);
}
其中components是存放虚拟Dom的数组,component是数组中得到的虚拟DOM,这里应该怎么修改ClassName
ihtml5
#4
className在render方法里是一个字符串对象,可以利用state或者 props,然后利用es6的模板语法进行字符串动态拼接,比如
// 通过this.state方式改变className
class ClsExample extends Component {
constructor(props) {
super(props);
this.state = {
cls: 'app'
};
}
render() {
return (<div className={`${this.state.cls}`}>app</div>);
}
}
// 通过this.props方式改变className
class ClsExample extends Component {
constructor(props) {
super(props);
this.state = {
cls: 'app'
};
}
render() {
return (<div className={`${this.props.cls}`}>app</div>);
}
}
<ClsExample cls={'app'}/>
Ad007
#6
render() {
this.debug('render ....');
this.components.push(<AttentionScreen ref="attention" message={this.state.message} />);
this.components.forEach(function(component, index) {
if(index > 0 && !component.classList.contains('hidden')) {
component.classList.add('hidden');
}
}, this);
return (<div> { this.components } </div>);
}