通过Navigator React Native传递参数

时间:2016-10-31 20:52:22

标签: android reactjs react-native navigator

我是React Native框架的新手,我有以下问题......

我有一个页面,其中包含一个导航器和两个文本输入,用于'用户名'和密码'。

我想将此用于登录,在此步骤中,只需将参数传递到下一页,然后输出到屏幕" Hello {username}"。

代码:

在FirstPage.js

class FistPage extends Component {
  constructor(props) {
    super(props);
    console.log('constructor');
    this.state = {
        username: '',
        password: ''
    }
  }

gotoNext() {
  if (this.state.username == '' || this.state.password == '') {
    Alert.alert(
      'Empty field(s)!',
      'Please fill username and password!',
      [
        {text: 'OK', onPress: () => console.log('OK Pressed')},
      ]
    )
  } else {
    this.props.navigator.push({
      id: 'SecondPage',
      name: 'Second Page',
      passProps: {
        username: this.state.username,
        password: this.state.password,
      }
    });
  }
}

我发现我可以使用passProps

在SecondPage.js中:

class SecondPage extends Component {
  constructor(props) {
    super(props);
    console.log('EmployeeManager - MainPage constructor');
    this.username = props.username;
    this.password = props.password;
  }


  renderScene(route, navigator) {
    return (
      <View style={{flex: 1, alignItems: 'center', justifyContent:'center'}}>
        <Text> Hello </Text>
        <TouchableHighlight style={{backgroundColor: 'yellow', padding: 10}}
          onPress={this.gotoPersonPage.bind(this)}>
          <Text style={{ color: 'black'}}>Hello {this.username}</Text>
        </TouchableHighlight>
      </View>
    );
  }

this.username为空。

如何从第一页传递用户名?

提前致谢!

EDIT。来自FirstPage.js的renderScene

renderScene(route, navigator) {
return (
<View style={{flex: 1, alignItems: 'center', marginTop: 90}}>
  <Text style={{textAlign: 'center', fontSize: 20}}>Welcome to    EmployeeManager! </Text>

  <Image source={require('./img/employees.png')} style={{width: 193, height: 130, marginTop: 10}}/>

  <TextInput placeholder='Enter username...'
             style={{width:200, textAlign: 'center'}}
             onChangeText={(text) => this.setState({...this.state, username: text})}/>

  <TextInput placeholder='Enter password...'
             style={{width:200, textAlign: 'center'}}
             secureTextEntry={true}
             onChangeText={(text) => this.setState({...this.state, password: text})}/>

<TouchableHighlight
    onPress={this.state.logged? this.exit.bind(this) : this.gotoNext.bind(this)}>
    <Image source= {this.state.logged? require('./exitButton.png') : require('./loginButton.png')} style={{marginTop: 10}}/>
</TouchableHighlight>

);

1 个答案:

答案 0 :(得分:0)

你能告诉我你的renderScene吗?在FirstPage中使用Navigator的那个。

您的renderScene看起来像这样:

renderScene(route,navigator){

        if ( route.id == 'SecondPage' ){
            return (<SecondPage 
                username={route.passProps.username}
                password={route.passProps.password} />);
        }
}