React类组件中如何从多个Input获取数据并存入localStorage?
Hey there! Let's fix up your Register component so it saves all the input fields (username, password, and phone number) to localStorage instead of just the username. I'll show you two approaches—one that builds on your current code, and a more React-native way that follows best practices.
Approach 1: Extend Your Current DOM Query Method
Right now you're using document.getElementById to grab the username input. We can just repeat this pattern for the other fields to get their values and store them:
submit(event) { // First, prevent the default form submission behavior (avoids page refresh) event.preventDefault(); // Grab each input element and its value const usernameInput = document.getElementById('username'); const passwordInput = document.getElementById('password'); const telInput = document.getElementById('tel'); const usernameValue = usernameInput.value; const passwordValue = passwordInput.value; const telValue = telInput.value; // Store each value individually in localStorage localStorage.setItem('username', usernameValue); localStorage.setItem('password', passwordValue); localStorage.setItem('tel', telValue); // Alternatively, store all data in a single object (easier to retrieve later) const userRegistrationData = { username: usernameValue, password: passwordValue, tel: telValue }; localStorage.setItem('userData', JSON.stringify(userRegistrationData)); }
This works, but it’s not the most React-friendly way because we’re directly manipulating the DOM. Let’s look at a better approach.
Approach 2: Use React Controlled Components (Recommended)
In React, controlled components keep form data in the component’s state. This lets React manage the form state, making it easier to add validation, real-time updates, and avoid direct DOM access. Here’s how to refactor your component:
class Register extends Component{ constructor(props) { super(props); // Initialize state to hold all form field values this.state = { username: '', password: '', tel: '' }; // Bind methods to the component instance this.submit = this.submit.bind(this); this.handleInputChange = this.handleInputChange.bind(this); } // Handle input changes for ALL fields with one function handleInputChange(event) { const { id, value } = event.target; this.setState({ [id]: value // Use computed property names to update the correct state key }); } submit(event) { event.preventDefault(); // Pull all values directly from state (no DOM queries needed!) const { username, password, tel } = this.state; // Store individually or as a single object localStorage.setItem('username', username); localStorage.setItem('password', password); localStorage.setItem('tel', tel); // Or store the entire state object (remember to stringify for localStorage) localStorage.setItem('userData', JSON.stringify(this.state)); } render(){ const { username, password, tel } = this.state; return( <div className="register-block"> <h4>Register</h4> <div className="register-block"> <InputGroup> <Input id="username" placeholder="username" value={username} onChange={this.handleInputChange} /> <Input id="password" placeholder="password" value={password} onChange={this.handleInputChange} type="password" // Add this to hide password input /> <Input id="tel" placeholder="tel number" value={tel} onChange={this.handleInputChange} /> </InputGroup> </div> <Button color="primary" onClick={this.submit}>Register</Button> </div> ) } }
Key Notes:
- Controlled Components: Each input’s
valueis bound to the component state, andonChangeupdates the state whenever the user types. This keeps React in full control of the form data. - Security Heads-Up: Storing plain-text passwords in localStorage is not secure for real-world apps. This is fine for an educational project, but in production, you’d send credentials to a backend for hashing and storage instead.
- Retrieving Data: If you stored the object with
JSON.stringify, you’d retrieve it later withJSON.parse(localStorage.getItem('userData')).
内容的提问来源于stack exchange,提问作者Sasha Zoria

