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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大大怪~将军

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值