我有单个按钮和一个项目列表。当我单击按钮时,我试图将类添加到列表中的第三个对象。我可以将班级设置为特定ID或孩子吗?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
bgColor: ''
}
}
jumpTo(e) {
// item = this.state.items[2];
//this.setState({ bgColor: 'blue' });
}
componentDidMount() {
axios.get('https://api.spacexdata.com/v2/launches')
.then((response) => {
//console.log(response.data)
this.setState({
items: response.data
})
})
.catch((err) => {
console.log('Error:', err);
})
}
render() {
const List = this.state.items.map((b, i) =>
<li key={i} id={'fn' + i}> Flight Number: {b.flight_number} and Mission_name: {b.mission_name}</li>
);
return (
<div>
<button onClick={this.jumpTo.bind(this)}></button>
<ul>
{List}
</ul>
</div>
);
}
}
render(<App />, document.getElementById("root"));
答案 0 :(得分:2)
id={'fn' + i}
如果你想以简单的方式做到这一点,你可以使用它
jumpTo(e)
{
document.getElementById("fn2").classList.add("classname");
}
或者你也可以这样做
jumpTo(e) {
const rawItem = this.state.items;
rawItem[2].classes = "classname";
this.setState({ items: rawItem });
}
render() {
const List = this.state.items.map((b, i) =>
<li key={i} id={'fn' + i} className={b.classes?b.classes:""}> Flight Number: {b.flight_number} and Mission_name: {b.mission_name}</li>
);