如何根据索引值将状态变量更改为true



当我点击关闭按钮时,val将立即变为Fruit。怎么做?例如

Apple          close
Grapes         close
Pineapples     close

否则,我们如何根据索引设置状态cancel为true。我的意思是,如果我点击了苹果的关闭按钮,只有那个索引值会为真,其他都是假的。我们能做到吗?

这是的样本代码


constructor(){
super();
this.state={
cancel: false;
}
}
<table>
<tr>
{
products.map((val, index)=>{
<td>{val} &nbsp; <button>closeIcon</button></td>
});
}
</tr>
</table>

if anyone help me how to solve this problem

  1. 这里我问了两个问题。

    Outof these you can answer one question.
    

我相信这就是你想要的,只有一种水果可以关闭

export default class Test extends React.Component {
constructor() {
super();
this.state = {
cancel: false,
products: [
{
name: "Apple",
closed: false
},
{
name: "Grapes",
closed: false
},
{
name: "Pineapples",
closed: false
}
]
};
this.onClick = this.onClick.bind(this);
}
onClick(e) {
this.setState((s) => ({
...s,
products: s.products.map((p) => ({
...p,
closed: p.name === e.target.name
}))
}));
}
render() {
return (
<table>
<tr>
{this.state.products.map((val, index) => {
return (
<td>
{val.closed ? "CLOSED" : "OPEN"} {val.name} &nbsp;{" "}
<button name={val.name} onClick={this.onClick}>
closeIcon
</button>
</td>
);
})}
</tr>
</table>
);
}
}

看一看https://codesandbox.io/s/silly-swirles-wfnks?file=/src/App.js

使所有可以关闭:

onClick(e) {
this.setState((s) => ({
...s,
products: s.products.map((p) =>
p.name === e.target.name ? { ...p, closed: true } : p
)
}));
}

https://codesandbox.io/s/tender-glade-6vg6b

您需要为中由贴图渲染的Button组件提供一个单独的状态。通过这种方式,您将能够为每个单独的Button组件设置State。将按钮包裹在单独的组件中

export default class ButtonComponent extends React.Component{
constructor(){
super();
this.state={
cancel: false;
}
}
onCancel = () => {
this.setState({...this.state, cancel: true})
}
render(){
return(
<td>{val} &nbsp; <button onClick={this.onCancel}>closeIcon</button>
</td>
)
}
}

render(){
return(
<table>
<tr>
{
products.map((val, index)=>{
<ButtonComponent key={index} />
});
}
</tr>
</table>
)
}

您不会从映射函数返回任何内容。修复后,只需在onClick上用this.setState更新状态即可完成

<tr>
{
products.map((val, index)=>{
return (<td>{val} &nbsp; <button>closeIcon</button></td>);
});
}
</tr>

请在此处查看jsfiddle,https://jsfiddle.net/qzmu5307/

编辑:如果你只想在关闭按钮时从列表中删除一个项目,你可以简单地从处于状态的数组中删除该项目(目前我是通过搜索数组中的值来执行此操作的,但这通常是一种糟糕的做法。为他们分配一些用于此提升的标识符)。