react 中获取多个input输入框中的值的 俩种写法

目录

1. 使用受控组件

2. 使用非受控组件


1. 使用受控组件

这是React中最常见的方法,每个输入框都与React组件的state相关联,并通过onChange事件来更新state。

代码示例:

import React, { Component } from 'react';

class MultipleInputExample extends Component {
  constructor(props) {
    super(props);
    this.state = {
      input1: '',
      input2: '',
      input3: ''
    };
  }

  handleInputChange = (event) => {
    const name = event.target.name;
    const value = event.target.value;

    this.setState({
      [name]: value
    });
  }

  handleSubmit = (event) => {
    event.preventDefault();
    const { input1, input2, input3 } = this.state;

    // 现在你可以在这里使用 input1、input2 和 input3 的值
    console.log('Input 1:', input1);
    console.log('Input 2:', input2);
    console.log('Input 3:', input3);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          name="input1"
          value={this.state.input1}
          onChange={this.handleInputChange}
        />
        <input
          type="text"
          name="input2"
          value={this.state.input2}
          onChange={this.handleInputChange}
        />
        <input
          type="text"
          name="input3"
          value={this.state.input3}
          onChange={this.handleInputChange}
        />
        <button type="submit">提交</button>
      </form>
    );
  }
}

export default MultipleInputExample;

2. 使用非受控组件

在这种方法中,你可以使用ref来获取输入框的值。这通常在需要与非受控库或DOM集成时使用。

代码示例:

import React, { Component } from 'react';

class MultipleInputExample extends Component {
  constructor(props) {
    super(props);
    this.inputRefs = {
      input1: React.createRef(),
      input2: React.createRef(),
      input3: React.createRef()
    };
  }

  handleSubmit = () => {
    const input1Value = this.inputRefs.input1.current.value;
    const input2Value = this.inputRefs.input2.current.value;
    const input3Value = this.inputRefs.input3.current.value;

    console.log('Input 1:', input1Value);
    console.log('Input 2:', input2Value);
    console.log('Input 3:', input3Value);
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.inputRefs.input1} />
        <input type="text" ref={this.inputRefs.input2} />
        <input type="text" ref={this.inputRefs.input3} />
        <button onClick={this.handleSubmit}>提交</button>
      </div>
    );
  }
}

export default MultipleInputExample;

猜你喜欢

转载自blog.csdn.net/XikYu/article/details/133941087