React Native:如何更改<Text>动态值 [英] React Native : how to change <Text> value dynamically

查看:39
本文介绍了React Native:如何更改<Text>动态值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to change value dynamically at some event

事件:

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

            this.setState({
                text: currentDistance                
            });                                   

    });
<Text>
   Moving : {this.state.text}
</Text>

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

does anyone know how to change text or any other method to achieve?

推荐答案

下面是一个例子,它使用状态在点击时动态改变文本值.您可以设置任何您想要的事件.

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>
      );
   }
}

使用 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;

这篇关于React Native:如何更改&lt;Text&gt;动态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆