Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setNativeProps Change Value for Text Component React Native Direct Manipulation

Tags:

react-native

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 I use to update the text component. I dont know if I am setting the right attribute/ how to figure out 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 attempt to explicitly assign the updated value:

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

( I know this this the proper way of doing things in RN ). I get the error "Cannot assign to read only property 'children' of object'#'"

So maybe this is why it cant be updated in RN for some reason ?

like image 983
Shivam Sinha Avatar asked May 04 '16 00:05

Shivam Sinha


People also ask

How do I change text input value in React Native?

TextInput needs value that it is the value that is gonna be shown inside the TextInput. And to update that value you use onChangeText that is gonna call whatever function you specify every time the text into the TextInput change.

Which method is used to modify the underlying native components directly?

It is sometimes necessary to make changes directly to a component without using state/props(or render whole hierarchies of components for a small change in one component). This process is called Direct Manipulation.

How do I override a function in React Native?

To override a style, you have two options. Either you can pass a style object, or you can pass a function that will obtain props regarding the current internal state of the component, thus enabling you to modify styles dynamically depending on the component state, such as isError or isSelected .

Can we use ref on component?

You may not use the ref attribute on function components because they don't have instances.


1 Answers

Instead of attempting to change the content of <Text> component. I just replaced with <TextInput editable={false} defaultValue={this.state.initValue} /> and kept the rest of the code the same. If anyone know how you can change the value of <Text> using setNativeProps OR other method of direct manipulations. Post the answer and ill review and accept.

like image 179
Shivam Sinha Avatar answered Sep 22 '22 10:09

Shivam Sinha