You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 handleName handler with name="email", which would update the email state property instead of keeping it synced with the name value.

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 email state property since we only need to track one value for syncing.
  • Renamed handleName to handleNameChange for clearer readability.
  • Updated the second input to use value={this.state.name} so it directly reflects the first input's content.
  • Added readOnly to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 18:07:38