问题描述
我正在创建一个跟踪商店库存的程序。我有一个项目名称(字符串)数组,我映射生成一个组件,为每个项目呈现一个标题以及相应的输入字段:
I'm creating a program to track store inventory. I have an array of item names (strings) that I map through to generate a component that renders a heading for each item along with a corresponding input field:
function Inventory(props){
let items = ['milk', 'bread', 'butter'],
itemInput = items.map((value,index) => {
return(
<div key={index}>
<h3>{value}</h3>
<input type={'text'} />
</div>
)
})
return(
<div>
{itemInput}
</div>
)
};
如何同时访问输入值以及相应的标题?例如,如果我在 milk
的输入中键入 5
,我希望能够同时访问 5
和牛奶
。
How can I access both the input value as well as well as its corresponding heading? For example, if I type 5
within the input for milk
, I want to be able to access both 5
and milk
.
我尝试过使用 refs
(最后只引用最后一个数组项),事件
和此
无济于事。任何建议都将不胜感激。
I've tried using refs
(which winds up referencing only the last array item), event
and this
to no avail. Any suggestions will be much appreciated.
推荐答案
可以使用onChange处理程序:
It is possible to use the onChange handler for this:
<input type="text" onChange={e => this.setState({ [value]: e.target.value })} />
状态现在看起来像这样:
The state now will look something like this:
{
milk: 5,
bread: 2,
butter: 10
}
这篇关于通过refs访问父级中无状态子组件的输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!