SetNativeProps Change the value for a text component. The response. Direct manipulation.

I want to directly update the value of a component due to performance reasons.

render(){ <View> <Text style={styles.welcome} ref={component => this._text = component}> Some Text </Text> <TouchableHighlight underlayColor='#88D4F5' style={styles.button}> <View> <Text style={styles.buttonText} onPress={this.useNativePropsToUpdate.bind(this)}> Iam the Child </Text> </View> </TouchableHighlight> </View> } 

This is the method that I use to update the text component. I do not know if I am setting the correct attribute / how to determine which attribute to set:

  useNativePropsToUpdate(){ this._text.setNativeProps({text: 'Updated using native props'}); } 

Essentially, trying to follow the same approach from this example: https://rnplay.org/plays/pOI9bA

Edit: When I try to explicitly assign an updated value:

 this._text.props.children = "updated"; 

(I know this is the right way to do things in RN). I get the error "Unable to assign read-only property to children of object" # ""

So maybe that’s why for some reason it can’t be updated in RN for some reason?

+7
source share
4 answers

Instead of trying to change the contents of the <Text> component. I just replaced <TextInput editable={false} defaultValue={this.state.initValue} /> and left the rest of the code the same. If anyone knows how you can change the value of <Text> using setNativeProps OR another direct manipulation method. Send an answer and review and accept.

+9
source

The text tag does not have text prop, therefore

 this._text.setNativeProps({ text: 'XXXX' }) 

does not work.

But the text tag has style prop, therefore

 this._text.setNativeProps({ style: { color: 'red' } }) 

work.

+2
source

A snippet of code to reset the value in the text box to blank.

 import React from 'react'; import { TextInput, Text, TouchableOpacity, View } from 'react-native'; export default class App extends React.Component { clearText = () => { this._textInput.setNativeProps({text: ''}); } render() { return ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}> <TextInput ref={component => this._textInput = component} style={{height: 50, width: 200, marginHorizontal: 20, borderWidth: 1, borderColor: '#ccc'}} /> <TouchableOpacity onPress={this.clearText}> <Text>Clear text</Text> </TouchableOpacity> </View> ); } } 

check this example here

0
source

Since setNativeProps does not solve the goal of changing the contents of <Text /> , I have used the approach below and works well. Create a Simple React component as shown below ...

 var Txt = React.createClass({ getInitialState:function(){ return {text:this.props.children}; },setText:function(txt){ this.setState({text:txt}); } , render:function(){ return <Text {...this.props}>{this.state.text}</Text> } }); 
-1
source

All Articles