将组件道具传递到 ReactJS/NextJS 中的字符串
Passing component props into a string in ReactJS/NextJS
我有以下组件
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}
的控制台日志
但是,我收到以下错误消息: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} + "`);
}
在函数组件中,它没有关于this
的上下文。为什么不像在 return 函数中使用的那样使用道具。
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>
);
}
我有以下组件
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}
但是,我收到以下错误消息: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} + "`);
}
在函数组件中,它没有关于this
的上下文。为什么不像在 return 函数中使用的那样使用道具。
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>
);
}