当使用 React 来创建表单时,我们可以像 Vue.js 一样实现双向绑定。具体步骤如下:

  1. 创建一个状态变量
    使用 React 的 Hooks 中的 useState 方法创建一个状态变量,用于存储表单输入的值。

    const [firstName, setFirstName] = useState('');
  2. 将表单控件的 value 属性与状态变量绑定
    将表单控件(如 input)的 value 属性设置为状态变量,确保表单控件的值与状态变量同步。

    <input value={firstName} />

    在此示例中,firstName 是我们在步骤 1 中定义的状态变量。

  3. 在 onChange 事件中更新状态变量
    当表单控件的值发生变化时,触发 onChange 事件。在事件处理程序中,使用 setFirstName 方法更新状态变量,以便它反映输入字段中的最新值。

    <input value={firstName} onChange={e => setFirstName(e.target.value)} />

    在此示例中,setFirstName 是我们在步骤 1 中定义的更新状态变量的方法。

以下是一个完整的示例:

import React, { useState } from 'react';

function Form() {
  const [firstName, setFirstName] = useState('');

  return (
    <div>
      <input
        type="text"
        value={firstName}
        onChange={e => setFirstName(e.target.value)}
      />
      <p>First Name: {firstName}</p>
    </div>
  );
}

在此示例中,我们创建了一个输入框,并将其与 firstName 状态变量绑定。每当输入框的值发生变化时,该变量的值也会随之更新,并显示在页面上。


Master the React form development skills and achieve two-way binding just like Vue.js. Here are the specific steps:

  1. Create a state variable
    Use the useState method from React Hooks to create a state variable for storing the input value of the form.

    const [firstName, setFirstName] = useState('');
  2. Bind the value attribute of the form control with the state variable
    Set the value attribute of the form control (e.g., input) to the state variable to ensure that the value of the form control stays synchronized with the state variable.

    <input value={firstName} />

    In this example, firstName is the state variable defined in step 1.

  3. Update the state variable in the onChange event
    When the value of the form control changes, trigger the onChange event. In the event handler, use the setFirstName method to update the state variable so that it reflects the latest value in the input field.

    <input value={firstName} onChange={e => setFirstName(e.target.value)} />

    In this example, setFirstName is the method defined in step 1 for updating the state variable.

Here is a complete example:

import React, { useState } from 'react';

function Form() {
  const [firstName, setFirstName] = useState('');

  return (
    <div>
      <input
        type="text"
        value={firstName}
        onChange={e => setFirstName(e.target.value)}
      />
      <p>First Name: {firstName}</p>
    </div>
  );
}

In this example, we created an input box and bound it to the firstName state variable. Whenever the value of the input box changes, the value of the variable will be updated accordingly and displayed on the page.