通过本机导航将数据传递回组件

时间:2020-03-02 19:51:09

标签: react-native react-navigation

我在实现App.js的地方主要有StackNavigator

export default class App extends Component {
  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator initialRouteName="Home">
          <Stack.Screen name="MainPage" component={MainPage} />
          <Stack.Screen name="Submit" component={Submit} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}

我想要做的是将数据从Submit组件传递到我的MainPage中,并在{{1 }}。

ScrollView看起来像这样。我想通过函数array: arr将节点添加到我的state的{​​{1}}中:

MainPage

我的Mainpage组件如下所示。在按钮addNode上,我想将数据从输入传递到state,将其添加到数组,然后在滚动视图中显示:

MainPage

当我从class MainPage extends Component { constructor(props) { super(props); this.state = { arr: [], liters: '', time: '', }; } addNode = (time, liters) => { if (this.state.time) { this.state.arr.push({calc: time + liters}); this.setState({time: ''}); this.setState({liters: ''}); } }; onPress = () => { this.props.navigation.navigate('Submit', {addNode: this.addNode}); }; render() { return ( <View> <ScrollView>{this.state.arr}</ScrollView> <TouchableOpacity onPress={this.onPress}> <Text>+</Text> </TouchableOpacity> </View> ); } } 组件中单击Submit时,此屏幕显示错误:

enter image description here

我的问题是,如何使用Submit将数据从MainPage组件传回到class Submit extends Component { constructor(props) { super(props); this.state = { liters: '', time: '', }; } goBack() { this.props.navigation.goBack(); this.props.navigation.state.params.addNode({ time: this.state.time, liters: this.state.liters, }); } render() { return ( <View> <Text>Form</Text> <TextInput onChangeText={time => this.setState({time})} value={this.state.time} /> <TextInput onChangeText={liters => this.setState({liters})} value={this.state.liters} /> <Button title="Submit" onPress={this.goBack} /> </View> ); } } 组件?我在这里做错什么了?

0 个答案:

没有答案