首页 > 解决方案 > React Navigation 在导航时通过函数调用传递数据

问题描述

我正在尝试传递一个变量(我可以这样做)并在导航发生后立即使用该变量运行一个函数。

函数获取输入字段的值。但是因为我将输入字段分配给我的变量,所以我在渲染方法上遇到了一些问题,因为它在导航后覆盖了数据,甚至不写它。它在手动输入时有效,但我也需要从相机传递这个变量(这也很好)。

主页

  onChange(obj) {
    const value = obj;
    if (value) {
     this.setState({
      buttonDisabled: false,
      text: value,
     });
    } else {
     this.setState({
      buttonDisabled: true,
      text: ''
    });
   }
  };


render() {
    const { navigation } = this.props;
    const scanCode = navigation.getParam('text', '');

    return (
      <View style={{padding: 30, paddingTop: 40}}>
        <TextInput autoFocus
          ref='queryInput'
          style={{height: 40}}
          placeholder="placeholder.."
          value={scanCode === '' ? this.state.text : scanCode}
          onChangeText={this.onChange.bind(this)}
          onSubmitEditing={this.runQuery}
        />
        <Button
          onPress={this.runQuery}
          title="run"
          color="#841584"
          accessibilityLabel="query"
          disabled={this.state.buttonDisabled}
        />
      <Button title='Camera' style={{position: 'absolute', bottom: 0, left: 0}} onPress={() => this.gotoCamera()}></Button>
      </View>
    );
  }
};

相机页面

gotoMainPage = () => {
        this.props.navigation.navigate('Home', {
            text: this.state.qrcode
        })
    }
    onBarCodeRead = (e) => this.setState({qrcode: e.data}, () => this.gotoMainPage());

是否可以从相机页面的主页中设置值的状态,或者我应该在这里做什么?

谢谢

标签: react-nativereact-navigation

解决方案


推荐阅读