如何申请入学课程?我必须使用else语句将类设置为null。如果我不提供else语句,我将收到错误。
https://fiddle.jshell.net/8wsr7xa1
class App extends React.Component {
constructor(props){
super(props)
this.state = {
active: null
}
}
onMouseEnter(item){
this.setState({active: item})
}
render(){
const items = [1,2,3,4,5];
return (
<div>
{items.map((obj,i) =>
<div
key={i}
style={this.state.active === obj ?
{backgroundColor: 'yellow'} : {}}
onClick={this.onMouseEnter.bind(this, obj)}>
{obj}
</div>
)}
</div>
);
}
}
答案 0 :(得分:0)
很难理解你的问题,但我认为这是你想要做的事情?
class App extends React.Component {
constructor(props){
super(props)
this.state = {
actives: []
}
}
onMouseEnter(item){
let actives = [].concat(this.state.actives);
if (actives.indexOf(item) === -1) { actives.push(item) }
this.setState({actives});
}
render(){
const items = [1,2,3,4,5];
return (
<div>
{items.map((obj,i) =>
<div
key={i}
style={this.state.actives.indexOf(obj) > -1 ?
{backgroundColor: 'yellow'} : {}}
onMouseEnter={this.onMouseEnter.bind(this, obj)}>
{obj}
</div>
)}
</div>
);
}
}
React.render(
<App name="World"/ >,
document.getElementById('app')
);