我如何将参数从组件传递到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>
    )
};

我正在尝试做到这一点,以便根据我单击的哪个按钮来记录更便宜或电流的价格。我该怎么做?

因为 handleSell方法称为返回另一个函数,因此您需要在SellCatalogLine组件中调用props.handleSell(currentprice)

即。

handleSell = (price) => (event) => {
   console.log(price);
}

并将其用作

<button type="submit" onClick = {props.handleSell(currentprice)}>List item at ${currentprice} </button>

如果handleSell方法未返回函数,则可以使用匿名函数。您可以致电props.handleSell(currentprice)

handleSell = (event, price) => {
    console.log(price);
}

并将其用作

<button type="submit" onClick = {(e) => props.handleSell(e, currentprice)}>List item at ${currentprice} </button>

相关内容

  • 没有找到相关文章

最新更新