[英]Use prop value when setting a useState object value
I am using react hooks useState to update an object.我正在使用反应钩子 useState 来更新 object。 I have a reusable component, which is just an input, that I am passing props to and an onChange handler that updates the state.
我有一个可重用的组件,它只是一个输入,我将道具传递给它和一个更新 state 的 onChange 处理程序。
How can i use the prop value "fooType" to dynamically update the state?如何使用道具值“fooType”动态更新 state? This is working other than
fooType
in fooType: e.target.value` not being recognized as a variable.这是
fooType
中的 fooType 以外的工作:e.target.value` 未被识别为变量。 Is there a way to refactor for this to work in this manner?有没有办法重构它以这种方式工作?
The input component:输入组件:
const Input = (props) => {
const { foo, foos, setFoos, fooType } = props;
return (
<input type='text'
placeholder={ foo }
value={ foo }
onChange={ (e) => setFoos({ ...foos, fooType: e.target.value }) } />
);
};
Here is the file where I am passing the props to three inputs这是我将道具传递给三个输入的文件
const InputGroup = (props) => {
// initial state
const [foos, setFoos] = useState({
foo1: 0, foo2: 0, foo3: 0
});
return (
<div>
<Input foo={ foos.foo1 }
fooType='foo1'
foos={ foos }
setFoos={ setFoos } />
<Input foo={ foos.foo2 }
fooType='foo2'
foos={ foos }
setFoos={ setFoos } />
<Input foo={ foos.foo3 }
fooType='foo3'
foos={ foos }
setFoos={ setFoos }/>
</div>
);
}
You are going to want to surround the fooType in [] to set a variable as key value.您将要包围 [] 中的 fooType 以将变量设置为键值。
onChange={ (e) => setFoos({ ...foos, [fooType] : e.target.value }) } />
As of the way you are writing it right now fooType is interpreted as a new key value.就您现在编写它的方式而言, fooType 被解释为一个新的键值。 But the above change should fix it.
但是上述更改应该可以解决它。
Add brackets to your [fooType] to make it the object key将括号添加到您的 [fooType] 以使其成为 object 键
onChange={ (e) => setFoos({ ...foos, [fooType]: e.target.value }) }
Here a sandbox so you can play with it: https://codesandbox.io/s/exciting-ritchie-ijxxb这是一个沙盒,您可以使用它: https://codesandbox.io/s/exciting-ritchie-ijxxb
you got your answer.. but i would suggest you better approach to this.你得到了你的答案..但我建议你更好地解决这个问题。
The input component:输入组件:
const Input = props => {
const { index, fields, setFields } = props;
return (
<input type='text'
placeholder={ fields[index].placeHolder }
value={ fields[index].value }
onChange={ e => {
let fieldsCopy = fields.slice() // shallow copy
fields[index].value = e.target.value
setFields(fieldsCopy.slice())
} } />
);
};
and for your 3 component code -对于您的 3 个组件代码-
const InputGroup = props => {
// initial state
const [fields, setFields] = useState([
{ value: 0, placeHolder: 'foo1' }
{ value: 0, placeHolder: 'foo2' }
{ value: 0, placeHolder: 'foo3' }
]);
return (
<div>
{
foos.map((element, index) => {
<Input
key={index}
index={ index }
fields={ fields }
setFields={ setFields }
/>
})
}
</div>
);
}
ask if it's not clear问是否不清楚
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.