Javascript 按 Enter 键后调用 onChange 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31272207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
to call onChange event after pressing Enter key
提问by Bill Lumbert
I am new to Bootstrap and stuck with this problem. I have an input field and as soon as I enter just one digit, the function from onChange
is called, but I want it to be called when I push 'Enter when the whole number has been entered. The same problem for the validation function - it calls too soon.
我是 Bootstrap 的新手,并被这个问题所困扰。我有一个输入字段,只要我输入一个数字,onChange
就会调用from 函数,但是我希望在输入整个数字后按“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
});
回答by wuct
According to React Doc, you could listen to keyboard events, like onKeyPress
or onKeyUp
, not onChange
.
根据React Doc,您可以收听键盘事件,例如onKeyPress
或onKeyUp
,而不是onChange
。
var Input = React.createClass({
render: function () {
return <input type="text" onKeyDown={this._handleKeyDown} />;
},
_handleKeyDown: function(e) {
if (e.key === 'Enter') {
console.log('do validate');
}
}
});
Update: Use React.Component
更新:使用 React.Component
Here is the code using React.Component which does the same thing
这是使用 React.Component 做同样事情的代码
class Input extends React.Component {
_handleKeyDown = (e) => {
if (e.key === 'Enter') {
console.log('do validate');
}
}
render() {
return <input type="text" onKeyDown={this._handleKeyDown} />
}
}
Here is the jsfiddle.
这是jsfiddle。
回答by Admir
You can use onKeyPress directly on input field. onChange function changes state value on every input field change and after Enter is pressed it will call a function search().
您可以直接在输入字段上使用 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()
}
}}
/>
回答by Luca
pressing Enterwhen the focus in on a form control (input) normally triggers a submit
(onSubmit) event on the form itself (not the input) so you could bind your this.handleInput
to the form onSubmit.
当焦点在表单控件(输入)上时按Enter通常会触发submit
表单本身(而不是输入)上的 (onSubmit) 事件,因此您可以将您this.handleInput
的表单绑定到 onSubmit。
Alternatively you could bind it to the blur
(onBlur) event on the input
which happens when the focus is removed (e.g. tabbing to the next element that can get focus)
或者,您可以将其绑定到blur
(onBlur) 事件上input
的焦点被移除时发生的事件(例如,跳转到下一个可以获得焦点的元素)
回答by onmyway133
You can use event.key
您可以使用 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>
回答by c-chavez
React users, here's an answer for completeness.
反应用户,这是完整性的答案。
React version 16.4.2
反应版本 16.4.2
You either want to update for every keystroke, or get the value only at submit. Adding the key events to the component works, but there are alternatives as recommended in the official docs.
您要么想为每次击键更新,要么仅在提交时获取值。将关键事件添加到组件中是可行的,但官方文档中推荐了替代方法。
Controlled vs Uncontrolled components
受控与非受控组件
Controlled
受控
From the Docs - Forms and Controlled components:
In HTML, form elements such as input, textarea, and select typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().
We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.
在 HTML 中,诸如 input、textarea 和 select 之类的表单元素通常会维护自己的状态并根据用户输入进行更新。在 React 中,可变状态通常保存在组件的 state 属性中,并且仅使用 setState() 进行更新。
我们可以通过使 React 状态成为“单一的事实来源”来将两者结合起来。然后呈现表单的 React 组件还控制后续用户输入时该表单中发生的事情。以这种方式由 React 控制其值的输入表单元素称为“受控组件”。
If you use a controlled component you will have to keep the state updated for every change to the value. For this to happen, you bind an event handler to the component. In the docs' examples, usually the onChange event.
如果您使用受控组件,则必须在每次更改值时保持状态更新。为此,您将事件处理程序绑定到组件。在文档的示例中,通常是 onChange 事件。
Example:
例子:
1) Bind event handler in constructor (value kept in state)
1) 在构造函数中绑定事件处理程序(值保持在状态中)
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
}
2) Create handler function
2) 创建处理函数
handleChange(event) {
this.setState({value: event.target.value});
}
3) Create form submit function (value is taken from the state)
3)创建表单提交函数(值取自状态)
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
4) Render
4) 渲染
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
If you use controlledcomponents, your handleChange
function will always be fired, in order to update and keep the proper state. The state will always have the updated value, and when the form is submitted, the value will be taken from the state. This might be a con if your form is very long, because you will have to create a function for every component, or write a simple one that handles every component's change of value.
如果您使用受控组件,您的handleChange
函数将始终被触发,以更新并保持正确的状态。状态将始终具有更新的值,并且在提交表单时,将从状态中获取该值。如果您的表单很长,这可能是一个骗局,因为您必须为每个组件创建一个函数,或者编写一个简单的函数来处理每个组件的值变化。
Uncontrolled
不受控制
From the Docs - Uncontrolled component
In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.
To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.
在大多数情况下,我们建议使用受控组件来实现表单。在受控组件中,表单数据由 React 组件处理。另一种选择是不受控制的组件,其中表单数据由 DOM 本身处理。
要编写不受控制的组件,您可以使用 ref 从 DOM 获取表单值,而不是为每个状态更新编写事件处理程序。
The main difference here is that you don't use the onChange
function, but rather the onSubmit
of the form to get the values, and validate if neccessary.
这里的主要区别在于您不使用onChange
函数,而是使用onSubmit
表单来获取值,并在必要时进行验证。
Example:
例子:
1) Bind event handler and create ref to input in constructor (no value kept in state)
1) 绑定事件处理程序并在构造函数中创建 ref 以输入(状态中没有保留值)
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.input = React.createRef();
}
2) Create form submit function (value is taken from the DOM component)
2)创建表单提交函数(取自DOM组件的值)
handleSubmit(event) {
alert('A name was submitted: ' + this.input.current.value);
event.preventDefault();
}
3) Render
3) 渲染
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
If you use uncontrolledcomponents, there is no need to bind a handleChange
function. When the form is submitted, the value will be taken from the DOM and the neccessary validations can happen at this point. No need to create any handler functions for any of the input components as well.
如果使用不受控制的组件,则无需绑定handleChange
函数。提交表单时,将从 DOM 中获取值,此时可以进行必要的验证。也无需为任何输入组件创建任何处理程序函数。
Your issue
你的问题
Now, for your issue:
现在,对于您的问题:
... I want it to be called when I push 'Enter when the whole number has been entered
...我希望在输入整数后按“Enter”时调用它
If you want to achieve this, use an uncontrolled component. Don't create the onChange handlers if it is not necessary. The enter
key will submit the form and the handleSubmit
function will be fired.
如果要实现此目的,请使用不受控制的组件。如果没有必要,不要创建 onChange 处理程序。该enter
键将提交表单并handleSubmit
触发该函数。
Changes you need to do:
你需要做的改变:
Remove the onChange call in your element
删除元素中的 onChange 调用
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
});
Handle the form submit and validate your input. You need to get the value from your element in the form submit function and then validate. Make sure you create the reference to your element in the constructor.
处理表单提交并验证您的输入。您需要从表单提交函数中的元素中获取值,然后进行验证。确保在构造函数中创建对元素的引用。
handleSubmit(event) {
// Get value of input field
let value = this.input.current.value;
event.preventDefault();
// Validate 'value' and submit using your own api or something
}
Example use of an uncontrolled component:
使用不受控制的组件的示例:
class NameForm extends React.Component {
constructor(props) {
super(props);
// bind submit function
this.handleSubmit = this.handleSubmit.bind(this);
// create reference to input field
this.input = React.createRef();
}
handleSubmit(event) {
// Get value of input field
let value = this.input.current.value;
console.log('value in input field: ' + value );
event.preventDefault();
// Validate 'value' and submit using your own api or something
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
回答by David Alsh
You can also write a little wrapper function like this
你也可以写一个像这样的小包装函数
const onEnter = (event, callback) => event.key === 'Enter' && callback()
Then consume it on your inputs
然后在您的输入上使用它
<input
type="text"
placeholder="Title of todo"
onChange={e => setName(e.target.value)}
onKeyPress={e => onEnter(e, addItem)}/>