【问题标题】:onClick function not working using context-apionClick 函数在使用 context-api 时不起作用
【发布时间】:2020-10-08 20:58:38
【问题描述】:

用于单击产品并拉出产品详细信息页面的handleDetail() 功能不起作用。我的 addToCart 函数工作正常,所以我不知道我错过了什么。

context.js:

state = {
  products: [],
  productDataDetail: productDataDetail,
};

getItem = (id) => {
  const product = this.state.products.find((item) => item.id === id);
  return product;
};

handleDetails = id => {
  const product = this.getItem(id);
  this.setState(() => {
    return { productDataDetail: product };
  });
};

render() {
  return (
    <ProductContext.Provider
      value={{
        ...this.state,
        handleDetails: this.handleDetails,
      }}
    >
      {this.props.children}
    </ProductContext.Provider>
  );
}

product.js:

<ProductConsumer>
  {(value) => (
    <Card className={classes.root}>
      <CardActionArea onClick={() => value.handleDetails(id)}>
  )}
</ProductConsumer>

产品数据:

export const productDataDetail = {
  id: 0,
  name: "Desk",
  img: desk,
  store: "Local Furniture Shop 1",
  price: 9.99,
  desc:
    "This sturdy desk is built to outlast years of coffee and hard work. You get a generous work surface and a clever solution to keep cords in place underneath.",
  inCart: false,
  count: 0,
  total: 0,
};

【问题讨论】:

    标签: javascript reactjs state react-context


    【解决方案1】:

    bind它:

            value={{
              ...this.state,
              handleDetails: this.handleDetails.bind(this)
            }}
    

    否则,当您调用 value.handleDetails 时,该函数将绑定到与您想要的上下文(组件的上下文)不同的上下文 (value)

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 2016-07-07
      相关资源
      最近更新 更多