我正在制作一个购物车,当我单击Add to cart
时,次数会增加,这是使用挂钩完成的,并且在以下Pricetag.jsx 中
import React from 'react'
import './Body.css'
import { useState } from 'react'
// import './Cart.js'
export default function Pricetag(props) {
const [count, setCartCount] = useState(0);
return (
<div>
<div className="card1">
<div className="image">
<img src={props.images} alt="" className='card-image' />
</div>
<div className="content">
<div className="name">
{props.name}
</div>
</div>
<div className="button">
<button className='btn no1' id='cartbutton' onClick={() => setCartCount(count + 1)} >
Add to cart
</button>
<br></br>
</div>
</div>
</div>
)
}
现在我想在其他jsx中使用count的值,
import React from 'react'
import './Body.css'
import image2 from './assets/cake9.jpeg'
import image9 from './assets/cake16.jpeg'
import Pricetag from './Pricetag'
export default function Body(props) {
return (
<>
<div className="headingbody">
<div></div>
{props.title}
</div>
<div className="cart">
<div className="number34"> ** here I want to show my count **</div>
<i class="fa-solid fa-cart-shopping"></i>
</div>
<hr className='latestline' />
<div className='container1'>
<Pricetag images={image10} name="Swimming cake" bold="Rs 345" cut="Rs 634" />
<Pricetag images={image11} name="Rossy cake" bold="Rs 345" cut="Rs 634" />
</div>
</>
)
}
你能告诉我如何使用从第一个到第二个的count值吗?
有几种方法可以使用:
- 状态管理:redux,zustand
- 使用React上下文
- 你可以通过道具传递值,但这会导致"地狱道具">
您必须将count状态传递给其他JSX文件(组件(。有一些方法:
- 导入JSX文件并调用Pricetag.JSX中的组件,然后将count作为道具传递
- 如果您无法使用Pricetag.jsx中的组件,请使用Context API、Redux、MobX等状态管理解决方案
兄弟,您可以从下面的文档中找到useContext API调用及其功能的描述和想法
https://www.geeksforgeeks.org/reactjs-usecontext-hook/
https://reactjs.org/docs/hooks-reference.html#usecontext