2016-12-14 39 views
4

我想在一些事件有關的動態變化值陣營本土:如何改變<Text>值動態

事件:

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

      this.setState({ 
       text: currentDistance     
      });         

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

沒有人知道如何改變文本或任何其他方法來實現呢?

+0

你到底想改變什麼?什麼事件? – Tikkes

+0

'this.setState({text:'Another Text'})'http://facebook.github.io/react-native/releases/0.38/docs/state.html – Cherniv

+0

我想更新在我的位置計算的距離事件 我有問題 更新,但它給我的錯誤稱爲: 不確定是不是一個函數(評估「this.setState({文字:currentDistance})」) –

回答

14

下面是使用狀態在點擊文本時動態更改文本值的示例。你可以設置你想要的任何事件。

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

我需要寫 UPDATETEXT =()=> { this.setState({myText:'My Changed Text'}) } 這段代碼在我的事件裏面嗎? –

+0

得到它我只需要調用updateText()與所需的參數 其工作男子 喜歡它! 謝謝... –

2

用途:用於

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

代替:

<Text></Text> 

然後你就可以改變文字是這樣的:

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