简体   繁体   English

React.js 设置输入值

[英]React.js setting value of input

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.我是 react.js 的初学者,这很了不起,但我面临一个真正的问题:我需要使用普通和纯 javascript 设置输入的值,但出于某种原因,react.js 无法按预期工作。 Take this example: open this URL http://autoescolalatorreta.wix.com/latorreta#!contact/c24vq举个例子:打开这个网址http://autoescolalatorreta.wix.com/latorreta#!contact/c24vq

You will see there is an "Email" input field which id is "CntctFrm2emailField".您将看到有一个“电子邮件”输入字段,其 ID 为“CntctFrm2emailField”。 I try to change the value of it using javascript with this code:我尝试使用带有以下代码的 javascript 更改它的值:

document.getElementById("CntctFrm2emailField").value = "testing@gmail.com";

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.但是由于某种原因,React.js 没有在其核心原因上更新此值,如果您尝试发送表单(单击“发送”按钮),您将看到它将显示一条错误消息,指出电子邮件未正确填写。 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 会看到新值。

So how can I change an input value and have React.js to update that value too?那么如何更改输入值并让 React.js 也更新该值呢?

For React 16 above solutions are not working.对于上面的 React 16,解决方案不起作用。 Check this issue from GitHub.从 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");

I have written and use this function to trigger the change state for the field:我已经编写并使用此函数来触发字段的更改状态:

function doEvent( obj, event ) {
    /* Created by David@Refoua.me */
    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 = "testing@gmail.com";
doEvent( el, 'input' );

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 value of the input.而不是输入的value Take a look at your browsers console, that's what react will log there.看看你的浏览器控制台,这就是 react 会在那里记录的内容。

Depending on your code, you can set the states value onKeyUp or similar with a function or fetch the new inputs value when the form is submitted.根据您的代码,您可以使用函数设置onKeyUp或类似的states value或者在提交表单时获取新的输入值。

I had a form that I needed to submit for some monitoring.我有一个表格需要提交以进行一些监控。 I did it like this:我是这样做的:

$("input[type=email]").value = "me@something.com"
$("input[type=email]").defaultValue = "me@something.com"
$("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.请注意,对于我登录的网站,我必须同时设置 value 和 defaultValue。 There was some extra validation logic bound to the input.value有一些额外的验证逻辑绑定到 input.value

First of all, you should never ever work with "document" object in React.js.首先,你永远不应该在 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.你也不应该访问 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.受控元素没有自己的状态,它们通过 props 获取所有数据,并通过引发事件通知数据的更改。 We are using "value" prop to set inputs value.我们正在使用“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.解决方案是我们必须动态处理输入字段的更改事件。

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" />

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 = "testing@gmail.com";

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. React 内置了更新输入值的函数。 Try that way.试试那个方法。

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

if the input is not in a html form, then you should do it this way:如果输入不是 html 形式,那么你应该这样做:

document.getElementById("CntctFrm2emailField")[0].value = "testing@gmail.com";

This should work这应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM