栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将多个参数传递给React中的事件处理程序

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将多个参数传递给React中的事件处理程序

您绑定的功能不正确

在构造函数中,您无需指定参数,只需要像

this.setDesc = this.setDesc.bind(this);

同样在onChange中,当您要将参数传递给函数时,请使用bind指定它,而不是作为参数传递并再次绑定它们。

onChange={this.setDesc.bind(this, i)}

您的整个代码看起来像

import React, {Component} from 'react'import 'bootstrap/dist/css/bootstrap.css';export default class PriceTable extends Component {  constructor(props, context) {    super(props, context);    this.state = {      pid: this.props.pid || "12345",      name: this.props.name || "name",      prices: this.props.prices || [        {count: 1, desc: 'one', price: 8.25},        {count: 6, desc: 'six', price: 7.60},        {count: 12, desc: 'twelve', price: 6.953}      ]    };    this.setPid = this.setPid.bind(this);    this.setName = this.setName.bind(this);    this.setCount = this.setCount.bind(this);    this.setDesc = this.setDesc.bind(this);    this.setPrice = this.setPrice.bind(this);    this.logDebug = this.logDebug.bind(this);    this._renderPriceRow = this._renderPriceRow.bind(this);  }  setPid(e) {    this.setState({pid: e.target.value})  }  setName(e) {    this.setState({name: e.target.value})  }  setCount(i, e) {    var newPrices = this.state.prices    newPrices[i].count = e.target.value    this.setState({prices: newPrices})  }  setDesc(i, e) {    var newPrices = this.state.prices    newPrices[i].sec = e.target.value    this.setState({prices: newPrices})  }  setPrice(i, e) {    var newPrices = this.state.prices    newPrices[i].price = e.target.value    this.setState({prices: newPrices})  }  _renderPriceRow(price, i) {    return (      <tr key={i}>        <td >          <input type="text" className="form-control" defaultValue={price.count} onChange={this.setCount.bind(this, i)}/>        </td>        <td >          <input type="text" className="form-control" defaultValue={price.desc} onChange={this.setDesc.bind(this, i)}/>        </td>        <td >          <input type="text" className="form-control" defaultValue={price.price} onChange={this.setPrice.bind(this, i)}/>        </td>      </tr>    );  }  render() {    return (      <div className="row">       ...      </div>    );  }}

您还可以利用
Arrow函数
来传递类似

onChange={(e) => this.setDesc(e,  i)}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/399652.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号