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

react 中获取多个input输入框中的值的 俩种写法_第1张图片

目录

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 (
      
); } } 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 (
      
); } } export default MultipleInputExample;

你可能感兴趣的:(react.js,javascript,前端)