简体   繁体   English

是否可以将 setValue 作为 function 传递给子组件

[英]Is it possible to pass setValue in react to child componenet as a function

I have the following setup in react, now it complains that setClose is not a function inside the add to cart.我在反应中有以下设置,现在它抱怨 setClose 不是添加到购物车中的 function 。 I am stuck as to how I would trigger the setclose useState from inside the add to cart componenet, I guess I can't pass it as a prop down to the child.我不知道如何从添加到购物车组件内部触发 setclose useState,我想我不能将它作为道具传递给孩子。 Not sure what to do at this point.不知道此时该做什么。

Thanks ahead of time提前谢谢

main component主要成分

const [close, setClose] = useState(true)

  const toggleCart = () => {
    setClose(!close)
  }

return (
  <AddToCart
    cartAdd={setClose}
  />
  {close ? <CartItems /> : null}
)

add to cart componenet添加到购物车

import React from "react"

import { useShoppingCart, formatCurrencyString } from "use-shopping-cart"

const AddToCart = ({ sku, setClose }) => {
  const { addItem } = useShoppingCart()
  const test = () => {
    setClose(false)
  }
  return (
    <div>
      <button onClick={(() => addItem(sku), test())}>ADD TO CART</button>
    </div>
  )
}

export default AddToCart
const [close, setClose] = useState(true)

  const toggleCart = () => {
    setClose(!close)
  }

return (
  <AddToCart
    cartAdd={toggleCart}
  />
  {close ? <CartItems /> : null}
)

const AddToCart = ({ sku, cartAdd }) => {
  const { addItem } = useShoppingCart()
  const handleButtonClick = () => {
     addItem(sku);
     cartAdd();
  }
 
  return (
    <div>
      <button onClick={handleButtonClick}>ADD TO CART</button>
    </div>
  )
}

use like this像这样使用

UPDATED更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM