使用React在文本框中的onKeyUp事件

时间:2018-10-22 16:12:45

标签: javascript reactjs

我有一个文本框,接受用户输入的值。在文本框中输入值并按Enter时,该值将从框中消失。因此,我正在文本框中实现onKeyUp,以便确认该值。我认为我没有在正确的位置使用onKeyUp事件。 CodeSandBox for testing

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectorValues: []
    };

    this.handleKeyUp = this.handleKeyUp.bind(this);
  }

  addSelectorValues = e => {
    e.stopPropagation();
    this.setState(prevState => ({
      selectorValues: [...prevState.selectorValues, ""]
    }));
  };

  removeSelectorValue(index) {
    this.setState({
      selectorValues: this.state.selectorValues.filter((_, i) => i !== index)
    });
  }

  handleSelectorValueChange = index => ({ target: { value } }) => {
    const selectorValues = [...this.state.selectorValues]; //makes separate copy of array.
    selectorValues[index] = value;
    this.setState({ selectorValues });
  };

  handleKeyUp(e) {
    if (e.keyCode === 13) {
      console.log(e.target.value);
    }
  }

  render() {
    const { selectorValues } = this.state;

    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <fieldset>
            <div>
              <label>Selector Values:</label>{" "}
              <button
                type="button"
                onClick={this.addSelectorValues}
                onKeyUp={this.handleKeyUp}
              >
                Add
              </button>
              {this.state.selectorValues.map((value, index) => (
                <input
                  key={index}
                  type="text"
                  value={value}
                  placeholder="Enter slector values"
                  onChange={this.handleSelectorValueChange(index)}
                  required
                />
              ))}
              <ul>
                {this.state.selectorValues.map((value, index) => {
                  return (
                    <li key={index}>
                      {value}
                      <button
                        onClick={this.removeSelectorValue.bind(this, index)}
                      >
                        Remove
                      </button>
                    </li>
                  );
                })}
              </ul>
              <br />
            </div>
          </fieldset>
        </form>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

为什么不只使用e.preventDefault()来阻止表单提交:

handleSubmit(e) {
  e.preventDefault();
  // They hit enter, which submitted the form.
  // Do anything you need to do here
}

查看更新的密码和框here