如何在 React 中按 Enter 时停止重新加载网页

问题描述 投票:0回答:1

我目前正在做一个简单的待办事项列表,我遇到一个问题,当我单击输入时,我的网站将重新加载,我预计这将添加一个新任务。

谢谢您的帮助。

handleSubmit = (event) => {
    event.preventDefault();
    if (!this.state.input) {
      alert("You need to write a task!");
      return;
    }
    this.props.addNewTask({
      id: Math.floor(Math.random() * 1000 + 1),
      value: this.state.input,
    });
    this.setState({ showAddTask: false, input: "" });
  };

  handleKeyDown = (event) => {
    event.preventDefault();
    if (event.key === "Enter") {
      this.handleSubmit(event);
    }
  };

  render() {
    return (
      <div className="main-add-task">
        {this.state.showAddTask ? (
          <form className="add-task-form">
            <input
              type="text"
              placeholder="Do homework at 3pm"
              onChange={this.handleChangeInput}
              autoFocus
            />
            <div className="change-button">
              <button type="button" onClick={this.handleCancel}>
                Cancel
              </button>
              <button type="button" onClick={this.handleSubmit}>
                Add task
              </button>
            </div>
          </form>
        ) : (
          <button onClick={this.handleShow}>Add Task</button>
        )}
      </div>
    );
  }
}

export default AddTask;

我尝试将

event.preventDefault();
添加到我的 2 个功能中

reactjs react-native keydown preventdefault
1个回答
0
投票

主要问题是

handleKeyDown
方法。

您当前正在使用

even.preventDefault()
,这会阻止默认输入点击/提交。然后你就打电话给
handleSubmit()

处理表单提交的更好方法可以是:

handleSubmit = (event) => {
  // Prevent default form submission (page reload) whic you're already doing
  event.preventDefault();
  
  if (!this.state.input) {
    alert("You need to write a task!");
    return;
  }
  
  this.props.addNewTask({
    id: Math.floor(Math.random() * 1000 + 1),
    value: this.state.input,
  });
  
  this.setState({ showAddTask: false, input: "" });
};

render() {
  return (
    <div className="main-add-task">
      {this.state.showAddTask ? (
        <form 
          className="add-task-form" 
          onSubmit={this.handleSubmit}  // Add this line
        >
          <input
            type="text"
            placeholder="Do homework at 3pm"
            onChange={this.handleChangeInput}
            value={this.state.input}  // add this to make it a controlled component
            autofocus
          />
          <div className="change-button">
            <button type="button" onClick={this.handleCancel}>
              Cancel
            </button>
            <button type="submit">  {/* change to type="submit" */}
              Add task
            </button>
          </div>
        </form>
      ) : (
        <button onClick={this.handleShow}>Add Task</button>
      )}
    </div>
  );
}

我要研究的另一个更新是使用钩子(useState / 等)。基于类/this.X --- 从我的角度来看可能会变得令人困惑

© www.soinside.com 2019 - 2024. All rights reserved.