React Native getting name of TextInput in OnChange

2020-07-15 15:36发布

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, target, and text

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?

I have 2 TextInputs like this

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

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

Thanks

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

}

3条回答
霸刀☆藐视天下
2楼-- · 2020-07-15 15:39

You cannot supply or mutate the props that have already been defined by the documentation.

Therefore you can create custom component for TextInput as

const TextInputComponent = ({value, onChangeText, name, ...props}) => (
    <TextInput
        value={value}
        onChangeText={(value) => onChangeText(name, value)} //... Bind the name here
        {...props}
    />
)

Usage as you would use normally

          onChangeValue = (name, value) => {
             console.log(name, value)
             // Set the state according to your needs here
          }

          <TextInputComponent
            value={this.state.value}
            onChangeText={this.onChangeValue}
            name={'Pritish'}
          />
查看更多
【Aperson】
3楼-- · 2020-07-15 15:52

Or you can simply do:

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

and then in ts file

handleChange(event,name){
    // whatever
}
查看更多
Root(大扎)
4楼-- · 2020-07-15 15:57

onChangeText={() => this.handelChange("yourStateName")}

handleChange = (yourStatename) => (inputtext) => { setState({ [yourStatename]: inputtext })

查看更多
登录 后发表回答