gpt4 book ai didi

reactjs - 如何更新表中特定行的状态 ReactJS

转载 作者:行者123 更新时间:2023-12-03 13:42:38 30 4
gpt4 key购买 nike

我在表格设置中有图标,这样当单击图标时,会呈现不同的图标。现在这工作正常,但我想为我单击的行中的特定行重新呈现不同的图标,而不是在每一行中重新呈现不同的图标。不知道我将如何去做这件事。这是我的代码:

import React from 'react';
import StarBorder from '@material-ui/icons/StarBorder';
import Star from '@material-ui/icons/Star';
import axios from 'axios';

class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
starIcon: true,
data: [],
}
}

componentDidMount() {

axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=true')
.then(res => {
const data = res.data;
this.setState({ data: data})
})
}

handleClick = () => {
this.setState(prevState => ({
starIcon: !prevState.starIcon
}));
}

render() {
return (
<div>
<table border="1">
<thead>
<tr>
<td>Rank</td>
<td>Name</td>
<td>Price</td>
</tr>
</thead>
<tbody>
{this.state.data.map((n) => {
return (
<tr>
<td> <span onClick={() => this.handleClick()}> {this.state.starIcon ? <StarBorder/> : <Star /> } </span> </td>
<td>{n.name}</td>
<td>{n.current_price}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
}

export default Test;

最佳答案

在我看来,您需要将 starIcon bool 值复制到与数据数组长度相同的数组中,或者将 bool 值集成到数据数组中。这是第二个选项的建议:

import React from 'react';
import StarBorder from '@material-ui/icons/StarBorder';
import Star from '@material-ui/icons/Star';
import axios from 'axios';

class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
}
}

componentDidMount() {

axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=true')
.then(res => {
const data = res.data;
this.setState({ data: data.map(x => ({...x, starIcon: true}) ) })
})
}

handleClick = (i) => {
this.setState(prevState => ({
data: prevState.data.map((x, key) => (key === i ? {...x, starIcon: !x. starIcon} : x) )
}));
}

render() {
return (
<div>
<table border="1">
<thead>
<tr>
<td>Rank</td>
<td>Name</td>
<td>Price</td>
</tr>
</thead>
<tbody>
{this.state.data.map((n, i) => {
return (
<tr>
<td> <span onClick={() => this.handleClick(i)}> {n.starIcon ? <StarBorder/> : <Star /> } </span> </td>
<td>{n.name}</td>
<td>{n.current_price}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
}

export default Test;

希望对你有帮助

关于reactjs - 如何更新表中特定行的状态 ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57463522/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com