我是 React 的新手并尝试添加基于数组的类,但是当我单击另一个按钮时,当我单击另一个按钮时,事件类应该留在最后一个按钮类中,我没有任何线索这样做。
class Child extends React.Component {
render(){
return(
<button
onClick={this.props.onClick}
className={`initClass ${this.props.isClass}`}>
{this.props.text}
</button>
)
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
newClass: null,
};
}
myArray(){
return [
"Button 1",
"Button 2",
"Button 3"
];
}
handleClick (myIndex,e) {
this.setState({
newClass: myIndex,
});
}
render () {
return (
<div>
{this.myArray().map((obj, index) => {
const ifClass = this.state.newClass === index ? 'active' : '';
return <Child
text={obj}
isClass={ifClass}
key={index}
onClick={(e) => this.handleClick(index,e)} />
})}
</div>
)
}
}
ReactDOM.render(<Parent/>, document.querySelector('.content'));
.active {
background: cyan;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div class='content'/>
最佳答案
将您的 newClass 设为一个数组,并在放入类时检查该索引是否存在于您的状态数组中。
constructor(props) {
super(props);
this.state = {
newClass: [], //an array
};
}
....
handleClick (myIndex,e) {
if(!this.state.newClass.includes(myIndex)){
this.setState({
newClass: [...this.state.newClass, myIndex],
});
}
}
....
render () {
const that = this;
return (
<div>
{this.myArray().map((obj, index) => {
const ifClass = that.state.newClass.includes(index) ? 'active' : '';
return <Child
text={obj}
isClass={ifClass}
key={index}
onClick={(e) => that.handleClick(index,e)} />
})}
</div>
)
}
....
因为你没有告诉你什么时候需要删除类,所以不要添加你应该从数组中提取一些索引的步骤。
关于javascript - 在 react 中添加基于索引数组的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47466716/