简体   繁体   中英

Reading input value always returns undefined ReactJS

When trying to read the input value it will always say undefined no matter what even if I do it in the console itself.

this is my code:

    render() {
        return (
            <div onLoad={Startup()}>
                <input onKeyUp={CheckInput} id={"messageinput"} placeholder={"Bericht verzenden..."}
                       className={"messageinput"}/>
                <img className={"messageinputoption"} src={require('./Images/defaultPF.png')}/>
                <img className={"messageinputoption"} src={require('./Images/defaultPF.png')}/>
                <img className={"messageinputoption"} src={require('./Images/defaultPF.png')}/>
            </div>
        );
    }
}

export default Server;

function CheckInput(event) {
    const input = document.getElementById("messageinput");

    if (event.keyCode === 13) {
        if (IsCommand(input.value)) {
            let command = CheckCommand(input.value.substring(1, input.value.indexOf(" ")), input.value.substring(input.value.indexOf(" ") + 1));
        } else {
            SendMessage(input.value);
        }

        input.value = "";
    }
}

I'm not able to replicate your problem with getElementById , but I suggest you use currentTarget to fetch the Element , thus making the CheckInput function more reusable. Just change the input variable declaration to:

const input = event.currentTarget;

Or, even better, rework your input to a controlled input. See https://reactjs.org/docs/forms.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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