【问题标题】:How to pass props to child compoent from parent in react-native?如何在 react-native 中将 props 从父组件传递给子组件?
【发布时间】:2018-12-28 15:40:00
【问题描述】:

是否知道如何在 react-native 中从父级向子组件发送道具。我在 react-native 中听说过。但不知道在 react-native 中。 我想要的是当用户按下实际上包含在可触摸不透明度的 onpress 事件中的 AddToCart 按钮时,应该将道具发送到另一个页面。Somone 告诉我有关使用 redux 的信息,但我认为这也可能发生在 react-native 中。

底线:按下时有一个按钮,道具应该被发送到另一个页面。

商品详情页面

应该从哪里发送道具。

cart() {
  let product_id = this.props.navigation.state.params.id;
  AsyncStorage.getItem('cart_id')
    .then((_id) => {
      API.post_data(_id, product_id)
        .then((data) => {
          if (data) {
            // this.props.navigation.navigate('Cart', {id: data.cart.id})
            // was using this method.But when I directly open
            // cart page it gives me an error undefined is not
            //  an object..blah blah
          }
        })
    })
}

<TouchableOpacity onPress={()=> { this.cart() }} >
    <Text>AddToCart<Text>
</TouchableOpacity>

购物车页面

应该在哪里接收道具。

componentDidMount() {
  let cart_id = this.props.navigation.state.params.id;
  // above method is just total waste.
  API.getCartItem(cart_id)
    .then((response) => {
    if (response) {
      this.setState({
        data: response
      });
    } else {
      alert('no data')
    }
  })
}

【问题讨论】:

  • an error undefined is not an object..blah blah 你得到的确切错误是什么?
  • @Tholle TypeError: undefined is not an object..(评估 this.props.navigation.state.params.id)
  • 您可以通过“this.props.navigation.navigate('Cart', {id: data.cart.id})”发送数据并接收检查 if(this.props.navigation. state.params.id){ car​​t_id = this.props.navigation.state.params.id }
  • 我成功获取了数据。但是如果我直接打开购物车页面而不点击 addToCart 按钮..它给我一个错误 undefined is not an object.(评估 this.props.navigation.state.params. id)
  • 创建一个正在更新并传递给子组件的本地状态。因此,当您按下按钮时,您会更新父组件中的状态,然后将更新后的状态传递给子组件。

标签: javascript reactjs react-native


【解决方案1】:

根据 React Navigation docs 这应该可以工作:

componentDidMount() {
  const { navigation } = this.props;
  // The 'NO-ID'  is a fallback value if the parameter is not available
  const cart_id = navigation.getParam('id', 'NO-ID');
  ...
}

【讨论】:

  • 感谢您的回复。使用该方法,只有错误消失了..但是用户也可以导航,包括 cart_id ...我想要的只是参数应该从父级传递到子级或从一个页面传递到另一个页面,而不让用户导航..只是参数...这可以在反应导航中实现吗
  • 所以您希望用户将商品添加到购物车而不必每次都导航到购物车页面?最干净的方法是使用 redux。但是如果你真的不想使用 redux,你可以在每个屏幕的状态下保留一个项目数组,比如 itemsInCart。然后,您可以在每次调用导航时将其传递到另一个屏幕。所以每个导航看起来都像 this.props.navigation.navigate('ScreenName', {id: data.cart.id})。我认为这真的很不方便,但我想不出不使用 redux 的其他方式。
  • 是的,我也认为这太不方便了。我对redux有点了解..那么如何在redux中管理这个??
猜你喜欢
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 2020-04-23
相关资源
最近更新 更多