在React中将onClick添加到提交按钮

时间:2018-10-31 23:10:20

标签: javascript reactjs events

我在此按钮上有反应

  {editing && (
    <Button extraClasses="m1" onClick={this.handleEditing} type="submit">
      Save
    </Button>
  )}

但是提交不起作用,如果我删除onClick,则提交有效。如何使onClick和Submit都能正常工作?

这是onSubmit事件:

  handleSubmit(e) {
    e.preventDefault();
    const params = this.state.params || this.props.selected.params;
    const { exportTypes } = this.props;
    const {
      startDate: startDateMoment,
      endDate: endDateMoment,
      companyId,
      exportTypeId,
      id,
    } = this.state;
    const type = exportTypes.find(o => o.id === Number(exportTypeId));
    let enrichedParams = [];

    if (type.params.length > 0) {
      enrichedParams = params.reduce((acc, { paramName, paramValue }) => {
        const { id: exportParameterId } = type.params.find(p => p.name === paramName);
        return [...acc, { exportParameterId, paramName, paramValue }];
      }, []);
    }

    const startDate = startDateMoment.format();
    const endDate = endDateMoment.format();
    const record = { companyId, exportTypeId, startDate, endDate, id, params: enrichedParams };
    const filteredQuery = Object.keys(record).reduce(
      (acc, k) => (record[k] ? { ...acc, [k]: record[k] } : acc),
      {},
    );
    if (!Object.keys(filteredQuery).length) return;
    this.props.updateExport(filteredQuery);
  }

1 个答案:

答案 0 :(得分:1)

您可以从onClick中删除Button事件处理程序,并在handleEditing方法内调用handleSubmit方法。

示例

class App extends React.Component {
  handleEditing = () => {
    // ...
  };

  handleSubmit = (e) => {
    // ...
    this.handleEditing();
  };

  render() {
    return (
      <div>
        {/* ... */}
        {editing && (
          <Button extraClasses="m1" type="submit">
            Save
          </Button>
        )}
        {/* ... */}
      </div>
    );
  }
}