NextJS:如何在点击产品时在组件头中显示产品的价格

w1e3prcc  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(206)

我是Nextjs(React)的新手。我创建了两个组件header.tsx和product.tsx。我在一个文件(组件)stepperLine.tsx中调用它们。我实际上想在标题中显示产品的价格。tsx组件当我点击“选择”的产品,我尝试了很多次,但我不能这样做。与ChatGPT相同。我希望你能帮助我。
下面我们来进一步了解一下我的担忧。
我的组件Header.tsx:这是我想在单击时显示产品价格的位置。

import { useRouter } from 'next/router';
import { Stepper } from 'react-form-stepper';
import { IoArrowBack } from 'react-icons/io5'

const Header = () => {
    const router = useRouter()
    return (
        <>
            <div className="fixed w-full bg-white top-0">
                <div className="flex items-center justify-between shadow-lg px-4 shadow-black-100">
                    <div>
                        <button type="button"
                                onClick={() => router.push('/')}
                                className='text-sm flex items-center font-semibold bg-transparent py-1.5 px-3 lg:px-7.5 navbutton rounded-full hover:bg-navyblue hover:text-white'>
                            <IoArrowBack className='mr-2'/>
                            Back to home
                        </button>
                    </div>
                    <div className="flex-auto w-64">
                        <Stepper
                            steps={[{}, {}, {}]}
                            activeStep={2}
                            className="font-bold text-sm"
                        />
                    </div>
                    <span className="font-bold text-xl border rounded-full border-black hover:border-green-500 hover:text-white cursor-pointer hover:bg-green-500 px-4">
                        {/* this is where i want to show the price */}
                         {String.fromCharCode(8355)}
                    </span>
                </div>
            </div>
        </>
    )
}

export default Header;

我的组件Product.tsx:这里的价格显示得很漂亮。这只是为了测试它是否有效。但我想在标题中显示它。

import Image from 'next/image'
import { AiOutlineCheckCircle } from 'react-icons/ai'
import data from '../../data/infographie.json';
import React from "react";

const Product = () => {

    const [product, setProduct] = React.useState(0);

    const choiseProduct = (priceProduct: number) => {
        setProduct(priceProduct)
        console.log(product)
    };
 
    return (
        <>
          <div className="grid gridCard grid-cols-2 md:grid-cols-3 gap-4">
              {
                data.map((items, i) => (
                    <div className='rounded-lg hover:outline-none hover:skew-x-1
                                transition-all hover:scale-80 hover:-translate-y-1 hover:ring-2 hover:ring-green-400 shadow flex flex-col justify-between hover:bg-green-50 hover:shadow-xl'
                                >
                      <Image width={300} height={300} className="h-54 max-w-full rounded-lg" src={items.image} alt="" />
                      <div className='mt-2'>
                          <span className="font-bold text-2xl m-6">{items.name}</span>
                          <button type="button" onClick={()=>choiseProduct(items.prix_unitaire)} className='text-sm m-4 flex items-center justify-center font-semibold bg-transparent py-1.5 px-3 lg:px-7.5 navbutton rounded-full hover:bg-navyblue hover:text-white'>
                           <AiOutlineCheckCircle className='mr-2' />
                               Choose
                          </button>
                        </div>
                     </div>
                    ))
               }
            </div>
             {/* the price is displayed nice and beautiful here. It's just for testing to see it works.*/}
            {product && (
                <span className="price p-4 bg-green text-white-font-bold">Prix: {product}</span>
             )}
        </>

    )
}

export  default Product;

我的组件调用其他两个组件:StepperLine.tsx

import React from 'react'
import { useRouter } from 'next/router'
import Header './header'
import Product './categories/product'
import User './categories/user'

const StepperLine = () => {
  
  const router = useRouter();
  let contentComponent;

  if (router.pathname === '/product') {
    contentComponent = <Product/>;
  } else if (router.pathname === '/user') {
    contentComponent = <User/>;
  }

  return (
      <>
          <Header/>
          {contentComponent}
      </>
  )
  
}
export default StepperLine;

“我希望能得到帮助。谢谢你。

zour9fqk

zour9fqk1#

有几种方法可以让你想到:

  • 使用二传手 prop 。
  • 使用context钩子
  • 使用redux

Redux对于像这样的小项目来说是大材小用了,但是如果你打算构建更复杂的东西,值得记住。
Context和Setter prop以类似的方式工作,将状态提升到最高父组件。我会给予你一个快速的想法如何二传手 prop 工程,让你研究其他的选择。
在StepperLine中声明一个状态变量,因为它是Product和Header的父变量:

const [price, setPrice] = React.useState();

然后修改产品组件以包含setter作为 prop 。这允许产品更新父状态:

const Product = ({priceSetter}) => { ...

另外修改choiseProduct以使用或新的setter prop:

priceSetter(priceProduct);

回到StepperLine,将state变量链接到Product上的新prop:

contentComponent = <Product priceSetter={setPrice}/>;

现在只需将状态从StepperLine传递到Header组件。在标题中添加一个属性:

const Header = (price) => { ...

并修改StepperLine以将状态传递给Header组件:

return (
  <>
      <Header price={price}/>
      {contentComponent}
  </>

最后,在Header组件中,您只需要显示价格

<span className="font-bold text-xl border rounded-full border-black hover:border-green-500 hover:text-white cursor-pointer hover:bg-green-500 px-4">
                    {/* this is where i want to show the price */}
                     {price}
                </span>

我还没有测试过这段代码,但希望这是足够的细节,让你开始。

相关问题