[英]How to pass parameter in a function on onClick event
我正在嘗試制作一個接受道具功能的組件。 我想在調用時將一些值傳遞給函數:
class Course extends Component {
render() {
return (
<div>
<div id="courses">
<p onClick={this.props.sumPrice}>{this.props.name}<b>{this.props.price}</b></p>
</div>
</div>
);
}
}
sumPrice
是在父組件中定義的函數,需要一個值。 這是我的sumPrice
函數和父類構造函數代碼:
constructor(props) {
super(props);
this.state = {
active: false,
total: 0
};
this.sumPrice = this.sumPrice.bind(this);
}
sumPrice(price) {
this.setState({ total: this.state.total + price });
}
通常,render中的Closure,arrow函數可以精確地處理這種情況:
<div id="courses">
<p
onClick={() => this.props.sumPrice(this.props.price)}
>
{ this.props.name }<b>{ this.props.price }</b>
</p>
</div>
盡管它可以按預期運行,但不幸的是,這是以犧牲性能為代價的。 為什么JSX道具不應該使用箭頭功能或綁定? 。 影響不一定是嚴重的問題,但通常應避免。
最佳解決方案是使用在每次重新渲染時都不會重新創建的函數,例如類方法:
class Course extends Component {
constructor(props) {
super(props)
this.onClick = this.onClick.bind(this)
}
onClick () {
const { sumPrice, price } = this.props
sumPrice(price)
}
render() {
return (
<div>
<div id="courses">
<p onClick={this.onClick}>{this.props.name}<b>{this.props.price}</b></p>
</div>
</div>
)
}
}
避免性能問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.