React Navigation - 将状态作为prop从受控组件传递到另一个组件

时间:2017-09-12 20:09:55

标签: react-native react-navigation

使用React Navigation库,我想将状态从受控组件作为prop传递给另一个组件进行显示。但是,我无法通过React Navigation库或React Training(StackNavigator)的React路由器实现这一目标。以下是使用React Navigation的代码:

// root component
class HomeScreen extends Component {

constructor(props) {
  super(props);
  this.state = {
    // no state yet
  };
}

    render() {

    return(
      <View></View>
    )
  }
} 

// stack navigation
const MyApp = StackNavigator({
  Home: { screen: Home },
  A: { screen: A },
  B: { screen: B },
  C: { screen: C },
  D: { screen: D },
}, 


// controlled component getting user input and saving as state
class B extends Component {

constructor(props) {
    super(props);
      this.state = {
        page:'B',
        query: '',
        showTextInput: true,
        showSearchResults: true,
        showSearchAgain: false,
        userSelection: '',
      }
    };

// other code in this component is receiving input as state query, 
matching it with a set of search terms, and taking the selection and 
setting it as state userSelection - all successfully

// the button in this code successfully navigates to component C - 
the only question is how to pass state userSelection to C? 
<TouchableOpacity onPress={() => navigate('C')}>
  <View style={styles.button}>
    <View style={styles.buttonTextAlign}>
       <Text style={styles.buttonText}>
          Button
       </Text>
    </View>
  </View>
</TouchableOpacity>

如何将组件B中的状态userSelection传递给组件C?非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以在导航到其他屏幕时发送参数。详细信息可在react-navigation docs中找到。

示例

<Button
    onPress={() => navigate('C', {name: 'Brent'})}
    title="Go to Brent's profile"
/>

// and in your C Component
console.log(this.props.navigation.state.params.name) // logs Brent