React Native : how to change value dynamically

前端 未结 2 1165
有刺的猬
有刺的猬 2021-02-01 04:43

I want to change value dynamically at some event

Event:

BackgroundGeolocation.on(\'location\', (location) => {      
    currentDistance =  distance(         


        
相关标签:
2条回答
  • 2021-02-01 05:32

    Use:

    <TextInput editable={false} ref={component=> this._MyComponent=component}/> 
    

    instead of:

    <Text></Text>
    

    Then you can change the text this way:

    onPress= {()=> {
        this._MyComponent.setNativeProps({text:'my new text'});
    }
    
    0 讨论(0)
  • 2021-02-01 05:41

    Below is the example where it uses states for dynamic changing of text value while clicking on it. You can set on any event you want.

    import React, { Component } from 'react'
    import {
       Text,
       View
    } from 'react-native'
    
    export default class reactApp extends Component {
       constructor() {
          super()
          this.state = {
             myText: 'My Original Text'
          }
       }
       updateText = () => {
          this.setState({myText: 'My Changed Text'})
       }
       render() {
          return (
             <View>
                <Text onPress = {this.updateText}>
                   {this.state.myText}
                </Text>
             </View>
          );
       }
    }
    

    EDIT: Using React Hooks

    import React, { useState } from 'react';
    import { View, Text } from 'react-native';
    
    const ReactApp = () => {
        const [myText, setMyText] = useState("My Original Text");
        return (
            <View>
                <Text onPress = {() => setMyText("My Changed Text")}>
                        {myText}
                </Text>
            </View>
        )
    }
    
    export default ReactApp;
    
    0 讨论(0)
提交回复
热议问题