从.map中包含的数据数组中启用单个按钮



单击INSIDE时需要您的帮助以启用按钮。map

以下是来自后端的数据:

文件:[{id: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>

))}

在UI中,它看起来像这样:

链接---------------按钮

我需要的是一个功能,当我点击第一个链接时,它只启用旁边的第一个按钮,我现在拥有的是,当我单击第一个链接,它启用所有按钮

请帮忙。感谢

将活动按钮索引添加到您的状态

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> 
))}

编辑以允许多个活动

将活动按钮索引对象添加到您的状态

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
}

最新更新