React Native:如何动态更改<Text>值

Rus*_*iya 21 react-native

我想在某些事件中动态更改值

事件:

BackgroundGeolocation.on('location', (location) => {      
    currentDistance =  distance(previousLatitude,previousLongitude,latitude,longitude);

            this.setState({
                text: currentDistance                
            });                                   

    });
<Text>
   Moving : {this.state.text}
</Text>
Run Code Online (Sandbox Code Playgroud)

有谁知道如何更改文本或任何其他方法来实现?

Nee*_*ala 31

下面是一个示例,它使用状态在单击时动态更改文本值.您可以根据需要设置任何事件.

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>
      );
   }
}
Run Code Online (Sandbox Code Playgroud)


小智 10

使用:

<TextInput editable={false} ref={component=> this._MyComponent=component}/> 
Run Code Online (Sandbox Code Playgroud)

代替:

<Text></Text>
Run Code Online (Sandbox Code Playgroud)

然后你可以这样改变文字:

onPress= {()=> {
    this._MyComponent.setNativeProps({text:'my new text'});
}
Run Code Online (Sandbox Code Playgroud)