如何解决从包含在.map中的数据数组启用单个按钮
在点击INSIDE .map
时需要有关启用按钮的帮助这是来自后端的数据:
文件:[
{
编号:1
颜色为橙色,
形状:三角形
}
{
id:2
颜色:蓝色
形状:圆形
}
{
id:3
红色,
形状:矩形
}
]
这是.map格式的文件:
{file.map(file =>( `<div>
<a
onClick={() => this.downloadFile(file)}
href="javascript:void(0);"
>
{file.fileName}
</a>
</div>
<Button
onClick={() => this.submit()}
disabled={should be enabled when click}
>
submit
</Button>
))}
在用户界面中,它看起来像这样:
LINK --------------按钮(已禁用)
LINK --------------按钮(已禁用)
LINK --------------按钮(已禁用)
我需要的是一个功能,当我单击第一个LINK时,它仅启用旁边的第一个按钮,而现在的功能是,当我单击第一个LINK时,它将启用所有按钮。
请帮助。谢谢
解决方法
将活动的按钮索引添加到您的状态
this.state = {
// ... any other state
activeButtonIndex: null,};
单击按钮时,将activeButtonIndex
设置为按钮的映射索引。还可以使用activeButtonIndex
与当前映射索引进行比较,并在它们匹配时禁用该按钮。
{file.map((file,index) => (
<div>
<a
onClick={() => this.downloadFile(file)}
href="javascript:void(0);"
>
{file.fileName}
</a>
<Button
onClick={() => {
this.submit();
this.setState({ activeButtonIndex: index }); // <-- set active index
}}
disabled={index === this.state.activeButtonIndex} // <-- check active index
>
submit
</Button>
</div>
))}
编辑以允许多个活动
将活动按钮索引 object 添加到您的状态
this.state = {
// ... any other state
activeButtonIndex: {},};
单击按钮后,将映射的索引添加到activeButtonIndex
对象。还可以使用activeButtonIndex
对象与当前映射索引进行比较,并在该索引位于activeButtonIndex
对象中时禁用按钮。
{file.map((file,index) => (
<div>
<a
onClick={() => this.downloadFile(file)}
href="javascript:void(0);"
>
{file.fileName}
</a>
<Button
onClick={() => {
this.submit();
this.setState(prevState => ({
activeButtonIndex: {
...prevState.activeButtonIndex,// <-- copy existing state
[index]: true,// <-- set active index
},}));
}}
disabled={this.state.activeButtonIndex[index]} // <-- check active index
>
submit
</Button>
</div>
))}
,
单击第一个链接时,应存储状态。它可以存储在localStorage或cookie中。然后,您必须在组件中对其进行检索。
或者,如果您的链接没有将用户重定向到另一个页面,则只需将状态存储在组件中。例如,
this.state = {
isClicked = true
}
,
希望您将加载的数据存储在状态中。您需要为每个按钮设置一个单独的切换
state = {
data : []
}
this.apiCallToGetData().then(res => {
//set all buttons to disabled by default
res.map(r => {r.disabled = true;})
this.setState({data: res})
});
在您的HTML中,将禁用的属性设为动态,然后将索引传递给downloadFile函数:
{file.map((file,index) => (
<div>
<a
onClick={() => this.downloadFile(file,index)}
href="javascript:void(0);"
>
{file.fileName}
</a>
<Button
onClick={() => this.submit()}
disabled={file.disabled}
>
submit
</Button>
</div>
))}
最后,修改downloadFile函数以在单击时更新按钮的禁用状态
downloadFile = (file,index) => {
let freshFiles = this.state.data;
freshFiles[index].disabled = false;
this.setState({data : freshFiles});
//the rest of your code
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。