问题
I want toggle class only click element. But now when i click anyone they are all active. And when i click a tag, i want add another class to card div. How should i update the code?
handleClick() {
const currentState = this.state.active;
this.setState({ active: !currentState });
}
<div className="container">
<div>
<h1>Components</h1>
<div>
<a href="#" onClick={this.handleClick.bind(this)} className= {this.state.active ? "card-icon active" : "card-icon"}>click</a>
<a href="#" onClick={this.handleClick.bind(this)} className= {this.state.active ? "list-icon active" : "list-icon"}>click</a>
</div>
</div>
<input type="text" placeholder="" className="input" onChange={(e)=>this.searchSpace(e)} />
<div className="card">
{items}
</div>
</div>
回答1:
You are only tracking the state with one variable (active), but you need to keep track of each state separately. Try this:
Updated to handle toggle:
handleClick() {
const currentState = this.state.active;
this.setState({ active: !currentState });
}
<div className="container">
<div>
<h1>Components</h1>
<div>
<a href="#" onClick={this.handleClick.bind(this)} className= {this.state.active ? "card-icon active" : "card-icon"}>click</a>
<a href="#" onClick={this.handleClick.bind(this)} className= {!this.state.active ? "list-icon active" : "list-icon"}>click</a>
</div>
</div>
<input type="text" placeholder="" className="input" onChange={(e)=>this.searchSpace(e)} />
<div className={this.state.active ? "card" : "list"}>
{items}
</div>
</div>
回答2:
You should be using multiple state variables and also use function to update the state, so when you set cart-icon to active the list-icon state does not change. See the example below. let me know if it helps.
class MyComp extends React.Component {
constructor(props) {
super(props);
this.state = {
cartIconActive: false,
listIconActive: false,
};
this.handleCartIconClick = this.handleCartIconClick.bind(this);
this.handleListIconClick = this.handleListIconClick.bind(this);
}
handleCartIconClick() {
this.setState((prevState) => ({
...prevState,
cartIconActive: !prevState.cartIconActive,
}));
}
handleListIconClick() {
this.setState((prevState) => ({
...prevState,
listIconActive: !prevState.listIconActive,
}));
}
render() {
const { cartIconActive, listIconActive } = this.state;
return (
<div className="container">
<div>
<h1>Components</h1>
<div>
<a
href="#"
onClick={this.handleCartIconClick}
className={cartIconActive ? 'card-icon active' : 'card-icon'}
>
click
</a>
<a
href="#"
onClick={this.handleListIconClick}
className={listIconActive ? 'list-icon active' : 'list-icon'}
>
click
</a>
</div>
</div>
<input
type="text"
placeholder=""
className="input"
onChange={(e) => this.searchSpace(e)}
/>
<div className="card">{items}</div>
</div>
);
}
}
来源:https://stackoverflow.com/questions/61955420/react-toggle-class