【问题标题】:React Native : how to change <Text> value dynamicallyReact Native:如何动态更改 <Text> 值
【发布时间】:2016-12-14 09:58:07
【问题描述】:

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

事件:

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

            this.setState({
                text: currentDistance                
            });                                   

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

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

【问题讨论】:

  • 您到底想改变什么?什么活动?
  • 我想更新在我的位置事件计算的距离,但它给了我一个错误,叫做:undefined is not a function (evalating 'this.setState({text:currentDistance})')
  • 只需编写一个函数 setState 并在您想要更改文本时调用它。这是我在 rnplay 中制作的一个简单示例:rnplay.org/apps/J417aA
  • 是的,我已经通过功能实现了感谢@NguyênHoàng

标签: react-native


【解决方案1】:

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

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;

【讨论】:

  • 我需要在我的事件中编写 updateText = () => { this.setState({myText: 'My Changed Text'}) } 这段代码?
  • 知道了,我只需要使用所需的参数调用 updateText(),它的工作人员喜欢它!!!!谢谢...
  • 如果输入字段为空,我需要在文本中显示验证消息。你可以参考这个并让我知道任何答案stackoverflow.com/questions/57157692/…
【解决方案2】:

用途:

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

代替:

<Text></Text>

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

onPress= {()=> {
    this._MyComponent.setNativeProps({text:'my new text'});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多