简体   繁体   中英

Passing component props into a string in ReactJS/NextJS

I have the following component

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>
  );  
}

I am trying to add an onClick named handleClick and for testing, I am trying to run a console log containing the following {props.name} has been added to the basket at a price of {props.price}

However, onClick I receive the following error: TypeError: undefined is not an object (evaluating '_this.props')

What is the process to fix this?

The code for the handleClick function is below.

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

In function component, it does not have context about this . Why don't use props as you have used in return function.

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>
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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