如何将数据从映射对象传递到 React 中的父组件?

我正在构建一个购物车应用程序,该应用程序将每个项目都作为卡片组件包含在内。我通过映射一些虚拟对象数据来渲染这些卡片,如下所示:


const Home = () => {

  const dummyData = [

    {

      id: 1,

      title: 'tshirt',

      price: 10

    },

    {

      id: 2,

      title: 'coat',

      price: 20

    }

  ]

  

  const RenderCards = () => {

    return (

      dummyData.map(

        (d) => {

          return (

            <Card key={d.id} title={d.title} price={d.price} handleAddToCart={handleAddToCart}/>

          )

        }

      )

    )

  }

  

  const handleAddToCart = () => {

    // maybe access id and price here?

  }

  

  return (

    <>

      <RenderCards />

    </>

  )

}

和Card正在渲染的组件:


const Card = ({id, title, price}) => {

  return (

    <>

      <div key={id}>

        <p>{title}</>

        <p>{price}</>

        <button onClick={handleAddToCart}>Add to cart</button>

      </div>

    </>

  )

}


现在单击每张卡片中的按钮,我想将数据(卡片的 ID 和商品的价格)发送回父组件Home。假设点击了第二张卡片,我想访问id并price进入Home.


编辑: 也许我没有说清楚,我想在handleAddToCart功能中访问点击卡的价格和 ID。


HUX布斯
浏览 105回答 2
2回答

至尊宝的传说

您可以向下传递处理程序并让孩子将详细信息传递给它,如下所示:items.map(item => <Item addToCart={addToCart} {...item} />)const Item = ({ id, name, addToCart }) =>&nbsp;&nbsp; <div>&nbsp; &nbsp; {name}&nbsp; &nbsp; <button onClick={() => addToCart(id)}>Add to Cart</button>&nbsp; </div>或者像这样传递一个包含值的回调:items.map(item => <Item addToCart={() => handleAddToCart(item.id)} {...item} />)const Item = ({ id, name, addToCart }) =>&nbsp;&nbsp; <div>&nbsp; &nbsp; {name}&nbsp; &nbsp; <button onClick={addToCart}>Add to Cart</button>&nbsp; </div>

慕田峪7331174

在<Home />组件中,首先您可以使用 as 引入一个新状态useState:const [selectedItem, setSelectedItem] = useState(null)然后向下传递道具,setSelectedItem以便能够在那里触发:<Card key={d.id} title={d.title} price={d.price} handleAddToCart={handleAddToCart}&nbsp; &nbsp; &nbsp; setSelectedItem={setSelectedItem} />然后在<Card />组件中用作:const Card = ({id, title, price, setSelectedItem}) => {&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <div key={id}>&nbsp; &nbsp; &nbsp; &nbsp; <p>{title}</>&nbsp; &nbsp; &nbsp; &nbsp; <p>{price}</>&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handleAddToCart();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setSelectedItem({ id, title, price});&nbsp; &nbsp; &nbsp; &nbsp; }}>Add to cart</button>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </>&nbsp; )}+1 建议:<Card />我会将一个属性中的详细信息传递给组件,如下所示:<Card key={d.id}&nbsp; &nbsp; &nbsp; data={d}&nbsp; &nbsp; &nbsp; handleAddToCart={handleAddToCart}&nbsp; &nbsp; &nbsp; setSelectedItem={setSelectedItem} />然后将内部解构为:const Card = (props) => {&nbsp; &nbsp;const { data, setSelectedItem, handleAddToCart } = props&nbsp; &nbsp;const { id, title, price } = data&nbsp; &nbsp;// more code}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript