如何从屏幕向堆栈导航器发送参数?

时间:2017-11-08 07:38:36

标签: react-native

我是新手来做出反应。 我在标签导航器中使用堆栈导航器;我必须在每个标签内导航多个屏幕。我能够将我的默认类HomePage中的参数发送到我的选项卡和堆栈导航器中的嵌套类。

export const MyApp = TabNavigator({
Asset: {
screen: AssetScreen,
},
Sensors: {
screen: sensorsStack,
},
Settings: {
    screen: settingStack
 },
}
export const sensorsStack = StackNavigator({
sensors : { screen: SensorScreen },
sensorDetails : { screen: SensorDetails }
});
export const settingStack = StackNavigator({
 settings: { screen: SettingsScreen },
 about : { screen: About },
 environment : { screen: Environment }
});

export default class HomePage extends Component {
constructor(props) {
  super(props);
  this.state = {
   assetID:'xyz',
   authToken:'xyzz'
  }
}
static navigationOptions = {
  header: null
};
render() {
    const screenProps = {
        asset: {
            assetID: this.state.assetID,
            authToken : this.state.authToken,
        },
    }
    return (
        <MyApp screenProps={screenProps} />
    );
}
}

现在,我想从&#39; SensorScreen&#39;中发送一个参数。传感器详细信息&#39;我尝试使用

发送参数
 NavigationActions.navigate({ routeName: 'sensorDetails' ,params: { sensorType:'Fuel',}});
来自&#39; SensorScreen&#39;类。但无法在传感器详细信息中获取参数。类。我怎么能通过这个参数?

1 个答案:

答案 0 :(得分:1)

有点迟到的答案但可能会帮助其他人在这里结束。 您可以尝试从sensorScreen导航到sensorDetails,导航并传递一些额外的变量,而不是使用NavigationActions。

this.props.navigation.navigate('SensorDetails',{sensorType:'Fuel'})

然后可以通过

在第二个屏幕中读取传递的对象
this.props.navigation.state.params.sensorType

在这些行中可以看到案例的最小例子。观察这是一个愚蠢的图标标签栏。但它保持这种方式,因为问题是关于每个选项卡上有堆栈的标签栏。并且可以轻松添加新标签。

import React,{Component} from 'react'
import { Text, View, Footer,Button } from 'react-native'
import {StackNavigator,TabNavigator} from 'react-navigation'

export class SensorScreen extends React.Component {
  render() {
    return (<Button
              onPress={() => this.props.navigation.navigate('SensorDetails',{sensorType:'Fuel'})}
              title="Go to Sensor Details"
            />)}}

export class SensorDetails extends React.Component {
  render() {
    return (<View>
              <Text>{this.props.navigation.state.params.sensorType}</Text>
            </View>);}
  }

const sensorsStack = StackNavigator({
  sensors : { screen: SensorScreen },
  SensorDetails : { screen: SensorDetails }
});

const MyApp = TabNavigator({
  Sensors: {
    screen: sensorsStack,
  },
});

export default class Nested extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
        <MyApp/>
    );
}
}

希望这有帮助。