我是新的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
});

当前回答

下面是使用基于类的组件的一个常见用例:父组件提供一个回调函数,子组件呈现输入框,当用户按Enter键时,我们将用户的输入传递给父组件。

class ParentComponent extends React.Component {
  processInput(value) {
    alert('Parent got the input: '+value);
  }

  render() {
    return (
      <div>
        <ChildComponent handleInput={(value) => this.processInput(value)} />
      </div>
    )
  }
}

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleKeyDown = this.handleKeyDown.bind(this);
  }

  handleKeyDown(e) {
    if (e.key === 'Enter') {
      this.props.handleInput(e.target.value);
    }
  }

  render() {
    return (
      <div>
        <input onKeyDown={this.handleKeyDown} />
      </div>
    )
  }      
}

其他回答

下面是使用基于类的组件的一个常见用例:父组件提供一个回调函数,子组件呈现输入框,当用户按Enter键时,我们将用户的输入传递给父组件。

class ParentComponent extends React.Component {
  processInput(value) {
    alert('Parent got the input: '+value);
  }

  render() {
    return (
      <div>
        <ChildComponent handleInput={(value) => this.processInput(value)} />
      </div>
    )
  }
}

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleKeyDown = this.handleKeyDown.bind(this);
  }

  handleKeyDown(e) {
    if (e.key === 'Enter') {
      this.props.handleInput(e.target.value);
    }
  }

  render() {
    return (
      <div>
        <input onKeyDown={this.handleKeyDown} />
      </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,因为它有时会被弃用。

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>
);

您还可以像这样编写一个小的包装器函数

const onEnter = (event, callback) => event.key === 'Enter' && callback()

然后在输入中消费它

<input 
    type="text" 
    placeholder="Title of todo" 
    onChange={e => setName(e.target.value)}
    onKeyPress={e => onEnter(e, addItem)}/>
//You can use onkeyup directly on input field

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