我有一个这样的状态,我正在设置active和class标记如下:
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属性。这就是为什么当您单击一个时,它们全部都被更改了。
state
尤其要注意,状态跟踪 哪个 元素处于活动状态的索引。当MyClickable被点击时,它告诉Container它的索引,Container更新state,随后isActive相应的财产MyClickable秒。
MyClickable
Container
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 src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.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> }