在反应中通过他们的名字获取变量

时间:2017-09-13 13:30:32

标签: javascript reactjs

我需要将input元素的值赋给变量,我的表单包含10个输入,每个输入都有唯一的id和相同数量的变量,这些变量具有与输入id相同的名称,我还指定了一个函数saveChanges()对所有输入onChange属性,类就像这样

class MainClass extends React.Component {
    render() {
        var field1 = "";
        var field2 = "";
        var date1 = "";
        var description = "";
        //...
        function saveChanges() {
            document.getElementsByClassName("inputs").onchange = function (event) {
                // tried to use window["variable name"] to access the variables but page broke and goes into repetitive reload
                // need to know that is there any other method to save the changed value to respective variable
                window[event.target.id] = event.target.value;
            }
        }
        function sendDetails() {
            // use the values of the variables and send through rest api
        }
        return (
            <div>
                lable1:
                <input id="field1" className="inputs" type="text" onChange={saveChanges } /><br />
                lable2:
                <input id="field2" className="inputs" type="text" onChange={saveChanges } /><br />
                date1:
                <input id="date1" className="inputs" type="text" onChange={saveChanges } /><br />
                Description:
                <textarea id="discription" className="inputs" onChange={saveChanges }>
                </textarea>
                //...
                <button id="sendDetails" onClick={sendDetails }>
                    Send
                </button>
            </div>
        );
    }
}

对此的任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:0)

您可以为输入指定名称,并使用event.target.name

访问该输入
class MainClass extends React.Component {
    render() {
        var field1 = "";
        var field2 = "";
        var date1 = "";
        var description = "";
        //...
        function saveChanges(e) {
            this.setState({[e.target.name]: e.target.value});
        }
        function sendDetails() {
            // use the values of the variables and send through rest api
            console.log(this.state);
        }
        return (
            <div>
                lable1:
                <input id="field1" name="field1" className="inputs" type="text" onChange={saveChanges } /><br />
                lable2:
                <input id="field2" name="field2" className="inputs" type="text" onChange={saveChanges } /><br />
                date1:
                <input id="date1" name="date1" className="inputs" type="text" onChange={saveChanges } /><br />
                Description:
                <textarea id="discription" className="inputs" onChange={saveChanges }>
                </textarea>
                //...
                <button id="sendDetails" onClick={sendDetails }>
                    Send
                </button>
            </div>
        );
    }
}