javascript - 如何在 onClick 事件的函数中传递参数
问题描述
我正在尝试制作一个接收功能作为道具的组件。我想在调用函数时将一些值传递给函数:
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 中的闭包箭头函数会完全按照需要处理这种情况:
<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>
)
}
}
避免性能问题。
推荐阅读
- python - 我的 for 循环中的计数器有什么问题?
- google-chrome - 使用脚本在 Chrome 上剪切和粘贴
- python - 如何在 django 中使用电话号码实现两步注册?
- javascript - Vue.js 分页计算未按预期工作
- javascript - 反应:为每个孩子添加一个事件侦听器并将一个引用传递给父母的事件处理程序 - 效率低吗?事件冒泡可能吗?
- excel - 使用 VBA-Selenium 将表格数据提取到不同的 Excel 工作表中
- reactjs - onChange 不适用于 FromControl React Bootstrap
- php - 在codeigniter 4中找不到错误类'Codeigniter \ Model'
- vue.js - 如果作为全局配置对象导入,如何从 element-ui 获取单个组件(轮播)?
- php - PHP MySQL array_pad() 在多维数组上显示 html 表中的值