如何在ReactJS中实现输入框值同步到另一个输入框?
Fixing Input Sync in Your React Component
Hey there! Let's get your input sync working properly. I can see exactly what you're aiming for—here's how to adjust your code to make the second input mirror the first one perfectly:
The Issues in Your Current Code
- Your second input has a hardcoded
value="@yahoo.com"instead of being tied to your component's state, so it can't update when the first input changes. - The second input is using the same
handleNamehandler withname="email", which would update theemailstate property instead of keeping it synced with thenamevalue.
Updated Code
import React, { Component } from "react"; import "./styles.css"; import { Form, Input, Button } from "semantic-ui-react"; class App extends Component { constructor() { super(); this.state = { name: "" }; // We don't need the `email` state since we're syncing to `name` } handleNameChange = event => { this.setState({ name: event.target.value }); }; render() { return ( <div className="App"> <Form> {/* First input: controls the `name` state */} <Input placeholder="Name" onChange={this.handleNameChange} name="name" value={this.state.name} /> {/* Second input: mirrors the `name` state, set to read-only since we don't want edits here */} <Input placeholder="Synced Content" value={this.state.name} readOnly /> </Form> <Button>Submit</Button> </div> ); } } export default App;
Key Changes Explained
- Removed the unused
emailstate property since we only need to track one value for syncing. - Renamed
handleNametohandleNameChangefor clearer readability. - Updated the second input to use
value={this.state.name}so it directly reflects the first input's content. - Added
readOnlyto the second input to prevent users from editing it (you can remove this if you want the second input to be editable, but keep in mind edits here won't sync back to the first input unless you add additional logic).
If you actually wanted the second input to show something like [name]@yahoo.com (e.g., typing "john" shows "john@yahoo.com"), you can adjust the second input's value like this:
<Input placeholder="Email" value={`${this.state.name}@yahoo.com`} readOnly />
That should cover exactly what you're trying to achieve!
内容的提问来源于stack exchange,提问作者Sandhya
相关产品推荐
相关产品推荐

