【问题标题】:React Navigation - pass state as a prop from controlled component to another componentReact Navigation - 将状态作为道具从受控组件传递到另一个组件
【发布时间】:2017-09-12 20:09:54
【问题描述】:

使用 React Navigation 库,我想将受控组件的状态作为道具传递给另一个组件进行显示。但是,我似乎无法使用 React Navigation 库或 React Training (StackNavigator) 中的 React Router 来实现这一点。下面是我使用 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?非常感谢!

【问题讨论】:

    标签: react-native react-navigation


    【解决方案1】:

    您可以在导航到其他屏幕时发送参数。详细信息可以在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
    

    【讨论】:

    • 非常感谢它的工作!不得不做&lt;TouchableOpacity onPress={() =&gt; navigate('C', {userSelection: this.state.userSelection})}&gt;
    • 你是否也熟悉如何在 React Router v4 中做到这一点?我真的被卡住了here too.
    猜你喜欢
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2020-03-12
    • 2019-08-08
    • 2021-01-02
    • 1970-01-01
    • 2018-09-28
    相关资源
    最近更新 更多