我正在使用 jsx React 并希望动态设置一个类,同时保持另一个类静态,所以我想要像下面这样的东西来保持类 type
但有一个额外的动态类 change
更改为类 big
或 small
或其他。
<p className="type {change}">{pokeType}</p>
有没有办法在不使用 element.setAttribute
或 document.getElementById...className
或 jQuery 的情况下执行类似的操作?或者只能通过 DOM 操作来完成这种事情?
最佳答案
您需要在组件状态中进行更改
:
this.setState({ change: 'myClass1'})
// will yield <p className="type myClass1">...</p>
<p className={`type ${this.state.change}`}>{pokeType}</p>
this.setState({ change: 'myClass2'})
// will yield <p className="type myClass2">...</p>
<p className={`type ${this.state.change}`}>{pokeType}</p>
关于javascript - 动态更改 React jsx 类,无需 DOM 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39459631/