通过 refs 访问来自父级无状态子组件的输入值 [英] Accessing input value from stateless child component in parent through refs

查看:33
本文介绍了通过 refs 访问来自父级无状态子组件的输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个程序来跟踪商店库存.我有一个项目名称(字符串)数组,我通过映射来生成一个组件,该组件呈现每个项目的标题以及相应的输入字段:

功能库存(道具){让物品 = ['牛奶', '面包', '黄油'],itemInput = items.map((value,index) => {返回(<div key={index}><h3>{值}</h3><input type={'text'}/>

)})返回(<div>{项目输入}

)};

输出截图

如何访问输入值及其相应的标题?例如,如果我在 milk 的输入中输入 5,我希望能够同时访问 5milk.

我尝试过使用 refs(最终只引用最后一个数组项)、eventthis 都无济于事.任何建议将不胜感激.

解决方案

可以为此使用 onChange 处理程序:

this.setState({ [value]: e.target.value })}/>

状态现在看起来像这样:

<代码>{牛奶:5,面包:2个,黄油:10}

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>
    )
};

Screenshot of output

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.

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.

解决方案

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 访问来自父级无状态子组件的输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆