如何从多个输入中获取数据并将其放入localStorage?应对

时间:2018-01-28 08:36:20

标签: javascript reactjs

class Register extends Component{
    constructor(props) {
        super(props);
        this.submit = this.submit.bind(this);
    }

    submit(event) {
    let username = document.getElementById('username');
    let usernameValue = username.value;
    localStorage.setItem('username', usernameValue);
    }
    render(){
          return(
            <div className="register-block">
                <h4>Register</h4>
                <div className="register-block">
                    <InputGroup>
                        <Input id="username" placeholder="username" />
                        <Input id="password" placeholder="password" />
                        <Input id="tel" placeholder="tel number" />
                    </InputGroup>
                </div>
                <Button color="primary" onClick ={this.submit}>Register</Button>
            </div>
        )
    }
}

//此时,我只能输入数据来自输入id =&#34;用户名&#34;。如何从其他输入获取数据并将其存储在localStorage中?其教育项目

2 个答案:

答案 0 :(得分:0)

您可以这样做:

let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
let phone = document.getElementById('tel').value;

let data = [];
data['username'] = username;
data['password '] = password;
data['phone '] = phone;

localStorage.setItem('userdata', JSON.stringify(data));

// To retrieve data try this
data = JSON.parse(localStorage.getItem('userdata'));

答案 1 :(得分:0)

首先,在反应中直接与DOM节点进行交互并不是一个好主意。其次,您可以控制所有输入,并在io_loop上提交数据,如提交

localStorage

假设您的class Register extends Component{ constructor(props) { super(props); this.submit = this.submit.bind(this); this.state={ username: '', password: '', tel: '' } } handleChange = (key, val) => { this.setState({[key]: val}) } submit(event) { localStorage.setItem('registerData', JSON.stringify(this.state)); } render(){ return( <div className="register-block"> <h4>Register</h4> <div className="register-block"> <InputGroup> <Input id="username" placeholder="username" onChange={(val) => this.handleChange('username', val)} /> <Input id="password" placeholder="password" onChange={(val) => this.handleChange('password', val)}/> <Input id="tel" placeholder="tel number" onChange={(val) => this.handleChange('tel', val)} /> </InputGroup> </div> <Button color="primary" onClick ={this.submit}>Register</Button> </div> ) } } 是自定义组件,您还必须查看How to pass data from child to parent component。另请检查Controlled Vs UnControlled Components in React