javascript - 如何在此 React 应用程序中设置编辑项目功能?

标签 javascript reactjs

我正在构建一个 React 应用程序来学习 React,它添加了收入、支出并记录交易。

我正在努力解决如何设置编辑条目的功能。

所以我为每个条目都有一系列条目。 Expenditure条目React类如下:

const Expenditure = React.createClass({
  renderExpenditure(key) {
    const details = this.props.cashbook[key];
    return(
      <tr className="item" key={key}>
        <td><strong>{details.name}</strong></td>
        <td><strong>{h.formatPrice(details.amount)}</strong></td>
        <td>{details.category}</td>
        <td>{details.type}</td>
        <td>{details.date}</td>
        <td><button className="remove-item" onClick={this.props.removeCashflow.bind(null, key, 'expenditure')}>Remove</button></td>
      </tr>
    );
  },
  render() {
    return(
      <div className="expenditure">
        <table id="exp-table">
          <tbody>
            {Object.keys(this.props.cashbook || {}).map(this.renderExpenditure)}
          </tbody>
        </table>
      </div>
    );
  }
});

主应用程序组件中的removeCashflow 如下所示:

removeCashflow(key, type) {
    this.state.cashbook[type][key] = null;
    this.setState({
      cashbook: { [type]: this.state.cashbook[type] }
    });
  },

有人对在 React 中设置编辑条目功能的最佳方法有任何指示或建议吗?

不确定从哪里开始。

谢谢:)

最佳答案

第一步是为您的条目创建一个单独的组件,假设为 Entry ;-)

您可以使用其属性和要更改的方法来调用入口组件,如下所示:

<Entry entry={this.props.cashbook[key]} key={key} id={key} onRemove={this.props.removeCashflow} onEdit={this.props.editEntry} />

入口组件的渲染函数与 renderExpenditure 函数的内容类似。要删除的按钮将触发一个名为 handleDelete 的方法,如下所示:

handleDelete() {
    this.props.onDelete(this.props.id, 'expenditure')
}

您的组件还将有一个与此类似的 handleEdit 方法:

handleEdit(someParams) {
    var editEntry = this.props.entry
    // perform the edit here
    this.props.onEdit(this.props.id, editEntry)
}

更新后的项目将由您的应用组件处理以替换旧的项目。

关于javascript - 如何在此 React 应用程序中设置编辑项目功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35252959/

相关文章:

javascript - 如何在 Protractor 中跳出for循环?

Javascript 显式 block

javascript - 无法在javascript中的另一个文本框中找到两个日期之间的差异

javascript - Breeze : populate the error property of SaveResult

google-analytics - React + 路由器 + Google 标签管理器

javascript - 为什么我的计数器在单击 Canvas 时无法工作?

javascript - 在 jQuery 中获取滚轮数量

javascript - 以编程方式使用时出现 Babelify sourceType 错误

javascript - 如何使 react Bootstrap 工具提示适合容器?

javascript - 如何正确更新 react 中的状态