Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

javascript - 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. Take this example: open this URL 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:

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.

So how can I change an input value and have React.js to update that value too?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For React 16 above solutions are not working. Check this issue from 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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...