我是新的Bootstrap和卡住了这个问题。我有一个输入字段,只要我输入一个数字,函数从onChange被调用,但我希望它被调用时,我按下' enter时,整个数字已被输入。验证函数也存在同样的问题——它调用得太快了。

var inputProcent = React.CreateElement(bootstrap.Input, {type: "text",
  //bsStyle: this.validationInputFactor(),
  placeholder: this.initialFactor,
  className: "input-block-level",
  onChange: this.handleInput,
  block: true,
  addonBefore: '%',
  ref:'input',
  hasFeedback: true
});

当前回答

你可以使用onKeyPress直接在输入字段。onChange函数在每次输入字段变化时改变状态值,在按下Enter后,它将调用一个函数search()。

<input
    type="text"
    placeholder="Search..."
    onChange={event => {this.setState({query: event.target.value})}}
    onKeyPress={event => {
                if (event.key === 'Enter') {
                  this.search()
                }
              }}
/>

其他回答

你可以使用event.key

function Input({onKeyPress}) { return ( <div> <h2>Input</h2> <input type="text" onKeyPress={onKeyPress}/> </div> ) } class Form extends React.Component { state = {value:""} handleKeyPress = (e) => { if (e.key === 'Enter') { this.setState({value:e.target.value}) } } render() { return ( <section> <Input onKeyPress={this.handleKeyPress}/> <br/> <output>{this.state.value}</output> </section> ); } } ReactDOM.render( <Form />, document.getElementById("react") ) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="react"></div>

我更喜欢onKeyUp,因为它只在键被释放时才会触发。另一方面,如果用户出于某种原因按下并按住键,onKeyDown将触发多次。例如,当监听“按下”Enter键发出网络请求时,您不希望多次触发该请求,因为代价可能很高。

// handler could be passed as a prop
<input type="text" onKeyUp={handleKeyPress} />

handleKeyPress(e) {
  if (e.key === 'Enter') {
    // do whatever
  }
}

另外,不要使用keyCode,因为它有时会被弃用。

//You can use onkeyup directly on input field

    const inputField = document.querySelector("input");
        inputField.addEventListener("keyup", e => {
         
            if (e.key == "Enter") {
                 console.log("hello");
            }
        });

防止输入提交表单的例子,在我的情况下,它是一个谷歌地图位置自动完成输入

<input
  ref={addressInputRef}
  type="text"
  name="event[location]"
  className="w-full"
  defaultValue={location}
  onChange={(value) => setLocation(value)}
  onKeyDown={(e) => {
    if (e.code === "Enter") {
      e.preventDefault()
    }
  }}
/>
const [value, setValue] = useState("");

const handleOnChange = (e) => {
    setValue(e.target.value);
};

const handleSubmit = (e) => {
    e.preventDefault();
    addTodoItem(value.trim());
    setValue("");
};

return (
    <form onSubmit={handleSubmit}>
        <input value={value} onChange={handleOnChange}></input>
    </form>
);