我有这样的状态,我正在设置 active
和 class
标志,如下所示:
constructor(props) {
super(props);
this.state = {'active': false, 'class': 'album'};
}
handleClick(id) {
if(this.state.active){
this.setState({'active': false,'class': 'album'})
}else{
this.setState({'active': true,'class': 'active'})
}
}
我有一个来自州的类名的项目列表:
<div className={this.state.class} key={data.id} onClick={this.handleClick.bind(this.data.id}>
<p>{data.name}</p>
</div>
这里如何更改特定 div 的类名?
最佳答案
下面是我认为您正在尝试做的事情的完整功能示例(带有功能片段)。
说明
根据您的问题,您似乎正在为所有元素修改 state
中的 1 个属性。这就是为什么当您单击一个时,所有这些都被更改。
请特别注意,状态会跟踪哪个元素处于事件状态的索引。当 MyClickable
被点击时,它告诉 Container
它的索引,Container
更新 state
,随后 适当的
属性。MyClickable
的 >isActive
例子
class Container extends React.Component {
state = {
activeIndex: null
}
handleClick = (index) => this.setState({ activeIndex: index })
render() {
return <div>
<MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />
<MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>
<MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>
</div>
}
}
class MyClickable extends React.Component {
handleClick = () => this.props.onClick(this.props.index)
render() {
return <button
type='button'
className={
this.props.isActive ? 'active' : 'album'
}
onClick={ this.handleClick }
>
<span>{ this.props.name }</span>
</button>
}
}
ReactDOM.render(<Container />, document.getElementById('app'))
button {
display: block;
margin-bottom: 1em;
}
.album>span:after {
content: ' (an album)';
}
.active {
font-weight: bold;
}
.active>span:after {
content: ' ACTIVE';
}
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="app"></div>
更新:“循环”
在回应有关“循环”版本的评论时,我认为问题是关于呈现 MyClickable
元素数组。我们不会使用循环,但是 map ,这在 React + JSX 中很典型。以下内容应该会为您提供与上面相同的结果,但它适用于元素数组。
// New render method for `Container`
render() {
const clickables = [
{ name: "a" },
{ name: "b" },
{ name: "c" },
]
return <div>
{ clickables.map(function(clickable, i) {
return <MyClickable key={ clickable.name }
name={ clickable.name }
index={ i }
isActive={ this.state.activeIndex === i }
onClick={ this.handleClick }
/>
} )
}
</div>
}
关于javascript - 在状态变化时 react 变化类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35224113/