React Native 在 OnChange 中获取 TextInput 的名称 [英] React Native getting name of TextInput in OnChange

查看:42
本文介绍了React Native 在 OnChange 中获取 TextInput 的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为多个 TextInput 制作一个通用的 onChange 处理程序.然而,当我访问事件时,我能得到的最好的是 event.nativeEvent,它有 3 个键.

I'm trying to make a general onChange handler for multiple TextInput s. However when I access the event, the best I can get is event.nativeEvent which has 3 keys.

eventCount、目标和文本

eventCount, target, and text

目标只是一个数字.我从文档中意识到名称"不是 TextInput 的道具.有没有办法将道具传递给 TextInput,以便我稍后可以在 onChange 中获取它,然后根据它设置状态?

target is only a number. I realize from the docs that 'name' is not a prop of TextInput. Is there a way to pass in a prop to the TextInput so I can get it later in onChange and then set the state based on that?

我有 2 个这样的 TextInput

I have 2 TextInputs like this

<TextInput 
          name='foo'
          keyboardType='numeric'
          maxLength={4}
          onChange={this.handleChange}
        />

<TextInput 
          name='bar'
          maxLength={4}
          onChange={this.handleChange}
        />

谢谢

这是我尝试将 id 放在 TextInput 上的尝试

Here is what I tried for putting id on TextInput

<TextInput 
          id='bar'
          name='bar'
          maxLength={4}
          onChange={this.handleChange}
        />

handleChange(e) {
console.log(e.target.id);
const {name, type, text} = e.nativeEvent;
this.setState({baths: text});

}

推荐答案

或者你可以简单地做:

<TextInput 
             keyboardType='numeric'
             maxLength={4}
             onChange={e => this.handleChange(e,'foo')}
           />
<TextInput 
             name='bar'
             maxLength={4}
             onChange={e => this.handleChange(e,'bar')}
           />

然后在 ts 文件中

handleChange(event,name){
    // whatever
}

如果您担心性能,可以使用数据集.data- 前面的任何属性都添加到 target.dataset 对象中.

If you are worried about performance, you can use datasets. Any attribute prepended by data- are added to target.dataset object.

<TextInput 
             data-name='foo'
             keyboardType='numeric'
             maxLength={4}
             onChange={this.handleChange}
           />
<TextInput 
             data-name='bar'
             maxLength={4}
             onChange={this.handleChange}
           />

然后在 ts 文件中

handleChange(event){
    const {name} = event.target.dataset
    // whatever
}

这篇关于React Native 在 OnChange 中获取 TextInput 的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆