【问题标题】:Passing component props into a string in ReactJS/NextJS将组件道具传递到 ReactJS/NextJS 中的字符串中
【发布时间】:2020-09-23 16:21:00
【问题描述】:

我有以下组件

import Link from "next/link";
import styles from "./product.module.css";

export default function Product(props) {
  return (
    <div className={styles.product}>
      <Link href={props.link}>
        <img src={props.img} alt={props.name} />
      </Link>
      <Link href={props.link}>
        <h3>{props.name}</h3>
      </Link>
      <span>{props.price}</span>
              <button onClick={handleClick}>
          Add to Bag 
        </button>
    </div>
  );  
}

我正在尝试添加一个名为 handleClick 的 onClick 并进行测试,我正在尝试运行包含以下 {props.name} has been added to the basket at a price of {props.price} 的控制台日志

但是,onClick 我收到以下错误:TypeError: undefined is not an object (evaluating '_this.props')

解决这个问题的过程是什么?

handleClick 函数的代码如下。

const handleClick = (e) => {
        console.log(`${this.props.name} + "added to basket at price of " + ${this.props.price} + "`);
}

【问题讨论】:

    标签: javascript reactjs onclick next.js react-props


    【解决方案1】:

    在函数组件中,它没有关于this 的上下文。为什么不使用你在 return 函数中使用的 props。

    export default function Product(props) {
        const handleClick = (e) => {
            console.log(`${props.name} + "added to basket at price of " + ${props.price} + "`);
        }
        
        return (
            <div className={styles.product}>
                <Link href={props.link}>
                    <img src={props.img} alt={props.name} />
                </Link>
                <Link href={props.link}>
                    <h3>{props.name}</h3>
                </Link>
                <span>{props.price}</span>
                <button onClick={handleClick}>
                    Add to Bag
                </button>
            </div>
        );
    }
    

    【讨论】:

    • 我最初试过这个,它说ReferenceError: Can't find variable: props
    • 函数在哪里声明?它将在我的编辑中起作用。
    • 函数在component/product.js文件中声明?是否应该在调用它的页面上声明?
    • 顺便说一句,如果你想在某个地方声明函数,请检查如何通过概念访问函数中的变量在js中闭包:stackoverflow.com/questions/111102/…
    • 它没有在其他地方声明,它在产品组件@Viet Dinh中声明
    猜你喜欢
    • 2020-09-08
    • 2021-10-06
    • 2022-07-19
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2022-01-08
    • 2021-03-18
    • 2019-08-06
    相关资源
    最近更新 更多