如何使用useState

时间:2020-06-01 20:45:08

标签: javascript reactjs

React的新特性,我希望使用useState,但只能应用于clicked元素。例如:

const [backgroundColor, setBackgroundColor] = useState({background: "green"});

在我的职能中,我有这样的东西:

function updateBackground(){
let updateColor = {background: "blue"};
setBackgroundColor(updateColor);
}

然后在我返回的JSX代码中

{subButtons.map(function(subButton, index){
   return (<div key={index} onClick={updateBackground} style={backgroundColor}>{subButton}</div>)
 })}

但这将将此功能应用于.map方法的所有生成的元素。

如何更新我的代码以应用于仅单击的元素?

谢谢。

3 个答案:

答案 0 :(得分:2)

您正在尝试管理父级中多个子级的离散状态。 @Denis Stukalov通过建议为每个孩子保留相应的状态数组来回答这个问题。这行得通,但我发现它在现实世界中很难很好地扩展。

我建议跟踪按钮本身内部的状态。

const BackgroundButton = (props) => {
  const [backgroundColor, setBackgroundColor] = React.useState({background: 'green'});
  const updateBackground = () => setBackgroundColor({background: 'blue'});
  return <div onClick={updateBackground} style={backgroundColor} {...props} />
};

const App = () => ['button1', 'button2', 'button3'].map(
  (subButton, index) => (
    <BackgroundButton key={index}>{subButton}</BackgroundButton>
  )
);

See this in action in this CodePen

答案 1 :(得分:1)

您应该使用数组而不是单个背景对象。像这样:

const subButtons = ['button1', 'button2', 'button3']
const [backgroundColors, setBackgroundColor] = useState(subButtons.map(() => { return { background: "green" } }))

function updateBackground(index){
  let newBackgroundColors = [...backgroundColors]
  newBackgroundColors[index] = { background: "blue" }
  setBackgroundColor([...newBackgroundColors])
}

return (subButtons.map(function(subButton, index){
 return (<div key={index} onClick={()=>updateBackground(index)} style={backgroundColors[index]}>{subButton}</div>)
}))

在游乐场观看:https://jscomplete.com/playground/s505358

答案 2 :(得分:0)

const [backgroundColor, setBackgroundColor] = useState("green");

function updateBackground(){
  let updateColor = "blue"
  setBackgroundColor(updateColor);
}

改为尝试