[英]How to change the state of only one element in a map?
I am learning react and I have stumbled upon a problem that I am trying to solve for several hours now but without any luck.我正在学习反应,我偶然发现了一个我试图解决几个小时但没有任何运气的问题。 I have an array of product sizes which I map to buttons.
我有一系列产品尺寸,我从 map 到按钮。 My goal is to change the state only of the last clicked button and to pass the value of the button to a variable.
我的目标是仅更改最后一次单击按钮的 state 并将按钮的值传递给变量。 Currently whenever clicked, all buttons change their state.
目前,无论何时单击,所有按钮都会更改其 state。
import React, { useState } from "react";
export default function Button() {
const sizes = [10, 11, 12, 13];
const [btnState, setBtnState] = useState(true);
const handleClick = () => setBtnState(!btnState);
return (
<div className="button-component">
{sizes.map((size, index) => (
<button className="btn" onClick={handleClick}>
{size} {btnState.toString()}
</button>
))}
</div>
);
}
The issue here is that there is only the single state value and all the mapped buttons use the same state in the same way.这里的问题是只有一个 state 值,并且所有映射的按钮都以相同的方式使用相同的 state。
Convert the btnState
to an object where the size
is a dynamic key.将
btnState
转换为 object,其中size
是动态键。
function Button() {
const sizes = [10, 11, 12, 13];
const [btnState, setBtnState] = useState({});
const handleClick = (size) => () => setBtnState(sizes => ({
...size,
[size]: !sizes[size]
}));
return (
<div className="button-component">
{sizes.map((size, index) => (
<button className="btn" onClick={handleClick(size)}>
{size} {String(!!btnState[size])}
</button>
))}
</div>
);
}
If you want only a single active state then store just the passed size
in the callback handler in state and check it's value when mapping.如果您只想要一个活动的 state 则仅将传递的
size
存储在 state 的回调处理程序中,并在映射时检查它的值。
function Button() {
const sizes = [10, 11, 12, 13];
const [btnState, setBtnState] = useState();
const handleClick = (size) => () =>
setBtnState(size);
return (
<div className="button-component">
{sizes.map((size, index) => (
<button className="btn" onClick={handleClick(size)}>
{size} {String(btnState === size)}
</button>
))}
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.