gpt4 book ai didi

javascript - 如何在 onClick 事件的函数中传递参数

转载 作者:行者123 更新时间:2023-11-28 14:32:18 29 4
gpt4 key购买 nike

我正在尝试制作一个接收函数作为 Prop 的组件。我想在调用函数时将一些值传递给函数:

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

最佳答案

通常渲染中的闭包、箭头函数会按照需要的方式处理这种情况:

<div id="courses">
<p
onClick={() => this.props.sumPrice(this.props.price)}
>
{ this.props.name }<b>{ this.props.price }</b>
</p>
</div>

虽然它按预期工作,但不幸的是,它的代价是性能损失 Why shouldn't JSX props use arrow functions or bind? 。这种影响不一定是严重问题,但通常应该避免。

<小时/>

最佳解决方案是使用每次重新渲染时不重新创建的函数,例如类方法:

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

避免性能问题。

关于javascript - 如何在 onClick 事件的函数中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50978788/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com