如何将参数从组件传递到React中的事件侦听器?

时间:2019-05-26 04:29:33

标签: reactjs event-handling react-props

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

我正在尝试使控制台根据我单击的按钮记录下来priceprice或currentprice。我该怎么办?

1 个答案:

答案 0 :(得分:0)

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

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>