簡體   English   中英

將 onClick 添加到 React 中的提交按鈕

[英]Add an onClick to a submit button in React

我有這個按鈕反應

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

但是提交不起作用,如果我刪除 onClick,則提交有效。 我怎樣才能讓 onClick 和提交都工作?

這是 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);
  }

您可以從Button刪除onClick事件處理程序,並handleEditing調用handleEditing方法中的handleSubmit方法。

例子

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM