首页 > 解决方案 > 如何在 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 });
}

标签: javascriptreactjscomponents

解决方案


通常,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>
        )
     }
  }

避免性能问题。


推荐阅读