如何将参数从组件传递到 React 中的事件侦听器?
How do I pass parameters from a component into an event listener in React?
在我的 App.jsx 中,我有一个事件处理程序和一个返回的组件:
handleSell = (price) => (event) => {
console.log(price);
}
render() {
return(
<SellCatalogLine
key = {item.ORDERID}
price = {item.PRICE}
title = {item.TITLE}
handleSell = {this.handleSell}/>
)}
我的组件如下所示:
function SellCatalogLine(props){
const currentprice = props.price
const cheaperprice = currentprice - 100;
return (
<div>
<h3>{props.title}</h3>
<p>Lowest Price: ${currentprice}</p>
<button type="submit" onClick = {() => props.handleSell(currentprice)}>List item at ${currentprice} </button>
<button type="submit" onClick = {() => props.handleSell(cheaperprice)}>List item at ${cheaperprice} </button>
</div>
)
};
我正在努力使控制台根据我单击的按钮记录 cheaperprice 或 currentprice。我该怎么做?
由于 handleSell
方法在调用时 return 是另一个函数,因此您需要在 SellCatalogLine
组件中调用 props.handleSell(currentprice)
。
即
handleSell = (price) => (event) => {
console.log(price);
}
并将其用作
<button type="submit" onClick = {props.handleSell(currentprice)}>List item at ${currentprice} </button>
如果 handleSell
方法没有 return 函数,那么您可以使用匿名函数。您可以在其中调用 props.handleSell(currentprice)
即
handleSell = (event, price) => {
console.log(price);
}
并将其用作
<button type="submit" onClick = {(e) => props.handleSell(e, currentprice)}>List item at ${currentprice} </button>
在我的 App.jsx 中,我有一个事件处理程序和一个返回的组件:
handleSell = (price) => (event) => {
console.log(price);
}
render() {
return(
<SellCatalogLine
key = {item.ORDERID}
price = {item.PRICE}
title = {item.TITLE}
handleSell = {this.handleSell}/>
)}
我的组件如下所示:
function SellCatalogLine(props){
const currentprice = props.price
const cheaperprice = currentprice - 100;
return (
<div>
<h3>{props.title}</h3>
<p>Lowest Price: ${currentprice}</p>
<button type="submit" onClick = {() => props.handleSell(currentprice)}>List item at ${currentprice} </button>
<button type="submit" onClick = {() => props.handleSell(cheaperprice)}>List item at ${cheaperprice} </button>
</div>
)
};
我正在努力使控制台根据我单击的按钮记录 cheaperprice 或 currentprice。我该怎么做?
由于 handleSell
方法在调用时 return 是另一个函数,因此您需要在 SellCatalogLine
组件中调用 props.handleSell(currentprice)
。
即
handleSell = (price) => (event) => {
console.log(price);
}
并将其用作
<button type="submit" onClick = {props.handleSell(currentprice)}>List item at ${currentprice} </button>
如果 handleSell
方法没有 return 函数,那么您可以使用匿名函数。您可以在其中调用 props.handleSell(currentprice)
即
handleSell = (event, price) => {
console.log(price);
}
并将其用作
<button type="submit" onClick = {(e) => props.handleSell(e, currentprice)}>List item at ${currentprice} </button>