Reaction Native text text with multiple text fields

I found the example code on the Facebook React Native page, which shows how to use setNativeProp to clear text with a button, but I don’t see how to do this with multiple text fields. Here is the code:

var App = React.createClass({ clearText() { this._textInput.setNativeProps({text: ''}); }, render() { return ( <View style={styles.container}> <TextInput ref={component => this._textInput = component} style={styles.textInput} /> <TouchableOpacity onPress={this.clearText}> <Text>Clear text</Text> </TouchableOpacity> </View> ); } }); 

The link seems to be fixed in the function, so it will always be aimed at the same TextInput block. How can I change the function to target any TextInput field that I specify?

+5
source share
2 answers

That should work. Note that the ref reference to TextInput must be the one you call from the clearText functino function.

 var App = React.createClass({ clearText(fieldName) { this.refs[fieldName].setNativeProps({text: ''}); }, render() { return ( <View style={styles.container}> <TextInput ref={'textInput1'} style={styles.textInput} /> <TouchableOpacity onPress={() => this.clearText('textInput1')}> <Text>Clear text</Text> </TouchableOpacity> <TextInput ref={'textInput2'} style={styles.textInput} /> <TouchableOpacity onPress={() => this.clearText('textInput2')}> <Text>Clear text</Text> </TouchableOpacity> </View> ); } }); 

Updated my answer to clear different fields.

+8
source

You can also use something like this to clear TextInput text.

 clearText(fieldName) { this.refs[fieldName].clear(0); }, 
+1
source

Source: https://habr.com/ru/post/1236533/


All Articles