Javascript React.js 设置输入值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30683628/
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
React.js setting value of input
提问by Sitepor500.com.br
I am a beginner with react.js and it's amazing but I am facing a real problem: I need to set the value of an input using plain and pure javascript but form some reason react.js is not working as expected. Take this example: open this URL http://autoescolalatorreta.wix.com/latorreta#!contact/c24vq
我是 react.js 的初学者,这很了不起,但我面临一个真正的问题:我需要使用普通和纯 javascript 设置输入的值,但出于某种原因,react.js 无法按预期工作。举个例子:打开这个网址http://autoescolalatorreta.wix.com/latorreta#!contact/c24vq
You will see there is an "Email" input field which id is "CntctFrm2emailField". I try to change the value of it using javascript with this code:
您将看到有一个“电子邮件”输入字段,其 ID 为“CntctFrm2emailField”。我尝试使用带有以下代码的 javascript 更改它的值:
document.getElementById("CntctFrm2emailField").value = "[email protected]";
But for some reason React.js is not updating this value on its core cause if you try to send the form (Clicking the SEND button) you will see that it will display an error message saying that email is not filled right. BUT once I click inside the email field and type any letter and click the SEND button it works fine, I mean, React.js sees the new value.
但是由于某种原因,React.js 没有在其核心原因上更新此值,如果您尝试发送表单(单击“发送”按钮),您将看到它会显示一条错误消息,指出电子邮件未正确填写。但是,一旦我在电子邮件字段内单击并输入任何字母并单击“发送”按钮,它就可以正常工作,我的意思是,React.js 会看到新值。
So how can I change an input value and have React.js to update that value too?
那么如何更改输入值并让 React.js 也更新该值呢?
回答by David Refoua
I have written and use this function to trigger the change state for the field:
我已经编写并使用此函数来触发字段的更改状态:
function doEvent( obj, event ) {
/* Created by [email protected] */
var event = new Event( event, {target: obj, bubbles: true} );
return obj ? obj.dispatchEvent(event) : false;
}
Use it like this:
像这样使用它:
var el = document.getElementById("CntctFrm2emailField");
el.value = "[email protected]";
doEvent( el, 'input' );
回答by Ajay Bhosale
For React 16 above solutions are not working. Check this issuefrom GitHub.
对于上面的 React 16,解决方案不起作用。从 GitHub检查此问题。
function setNativeValue(element, value) {
let lastValue = element.value;
element.value = value;
let event = new Event("input", { target: element, bubbles: true });
// React 15
event.simulated = true;
// React 16
let tracker = element._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
element.dispatchEvent(event);
}
var input = document.getElementById("ID OF ELEMENT");
setNativeValue(input, "VALUE YOU WANT TO SET");
回答by baao
You should post your code in order to get a better/ more to your situation suited answer, but one think that will work is just setting the
您应该发布您的代码以获得更好/更适合您情况的答案,但有人认为这只是设置
defaultValue
instead of valueof the input. Take a look at your browsers console, that's what react will log there.
而不是value输入。看看你的浏览器控制台,这就是 react 会在那里记录的内容。
Depending on your code, you can set the statesvalueonKeyUpor similar with a function or fetch the new inputs value when the form is submitted.
根据您的代码,您可以使用函数设置或类似,或者在提交表单时获取新的输入值。statesvalueonKeyUp
回答by Kenny Cason
I had a form that I needed to submit for some monitoring. I did it like this:
我有一个表格需要提交以进行一些监控。我是这样做的:
$("input[type=email]").value = "[email protected]"
$("input[type=email]").defaultValue = "[email protected]"
$("input[type=password]").value = "mystellarpassword"
$("input[type=password]").defaultValue = "pinpmystellarpasswordss"
$("input[type=email]").dispatchEvent(new Event('input', {target: $("input[type=email]"), bubbles: true} ));
$("input[type=password]").dispatchEvent(new Event('input', {target: $("input[type=password]"), bubbles: true} ));
$("button.login").click()
Note that for the website I was logging into, I had to set both value and defaultValue. There was some extra validation logic bound to the input.value
请注意,对于我登录的网站,我必须同时设置 value 和 defaultValue。有一些额外的验证逻辑绑定到 input.value
回答by Yilmaz
First of all, you should never ever work with "document" object in React.js. It is a big no no. You should not access DOM element neither, but if you know what you are doing(like animations) you should create "ref" object, which is off the topic, to access DOM element.
首先,你永远不应该在 React.js 中使用“文档”对象。这是一个很大的不。你也不应该访问 DOM 元素,但是如果你知道你在做什么(比如动画),你应该创建“ref”对象,这与主题无关,以访问 DOM 元素。
First thing you should have an object inside the state object for your form. Lets say you have "username" and "password" fields in your form.
首先,您应该在表单的状态对象内有一个对象。假设您的表单中有“用户名”和“密码”字段。
state={form:{username:"","password:""}
Because input fields have their own state, whatever we type in there will be stored in the input field. We should get rid of the state of input field and only rely on the state object. We want to have single source of truth so convert "input" to “controlled element”. Controlled elements do not have their own state, they get all data, via props and they notify changes to the data by raising events. We are using "value" prop to set inputs value. Since input fields are initialized as empty strings, we will not be able to type something inside input field. Solution is we have to handle the change event for input fields dynamically.
因为输入字段有自己的状态,所以我们在那里输入的任何内容都将存储在输入字段中。我们应该摆脱输入字段的状态,只依赖状态对象。我们希望拥有单一的事实来源,因此将“输入”转换为“受控元素”。受控元素没有自己的状态,它们通过 props 获取所有数据,并通过引发事件通知数据的更改。我们正在使用“value”道具来设置输入值。由于输入字段被初始化为空字符串,我们将无法在输入字段中输入内容。解决方案是我们必须动态处理输入字段的更改事件。
handleChange=e=>{
const form={...this.state.form}
form[e.currentTarget.name]=e.currentTarget.value
this.setState({account})}
<input value={this.state.form.username} change={this.handleChange} name="username"/>
<input value={this.state.form.password} change={this.handleChange} name="password" />
回答by Ali Al Amine
if the input is not in a html form, then you should do it this way:
如果输入不是 html 形式,那么你应该这样做:
document.getElementById("CntctFrm2emailField")[0].value = "[email protected]";
document.getElementById("CntctFrm2emailField")[0].value = "[email protected]";
This should work
这应该工作
回答by jmingov
This is the key in your question,
这是你问题的关键,
But for some reason React.js is not updating this value on its core
但出于某种原因,React.js 并没有在其核心更新这个值
The main reason is that react works within a 'shadow dom', and your
主要原因是 react 在“shadow dom”中起作用,而您的
document.getElementById("CntctFrm2emailField").value = "[email protected]";
Inst updating the reacts value in any way just the window dom object.
Inst 以任何方式更新 reacts 值,只是窗口 dom 对象。
React has built in functions to update the value of the input. Try that way.
React 内置了更新输入值的函数。试试那个方法。
Check this page for more info about react forms: https://facebook.github.io/react/docs/forms.html#controlled-components
查看此页面以获取有关反应表单的更多信息:https: //facebook.github.io/react/docs/forms.html#controlled-components

