react 获取多个Input框中的值

在React中,当页面包含大量Input元素时,逐一处理值会导致代码冗余。本文介绍了两种方法来解决这一问题:一是通过name属性动态设置state;二是利用ref获取DOM节点内的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

react 获取多个Input框中的值

假如页面中有很多input需要取值,如果数量少的话,可以一个一个的定义,但是如果数据多的话一个一个的处理,会造成代码冗余,工作量大的问题。

方法1

关键点就是我们传递一下name值,然后去setState里动态设置每个input的值,我们可以在render里边console.log(this.state)看一下,我们的每一项的值就是{name1:”abc”,name2:”def”}

import React,{ Component } from 'react';
class ReplenishData extends Component{
    constructor(props){
        super(props);
        this.state = {}
    }
    showVal(name,e){
        this.setState({
            [name]:e.target.value
        });
    }
    render(){
        console.log(this.state);
        return(
            <div>
                <input type="text" onChange= {this.showVal.bind(this,"name1")} />
                <input type="text" onChange={this.showVal.bind(this,"name2")} />
                <input type="text" onChange={this.showVal.bind(this,"name3")} />
                <input type="text" onChange={this.showVal.bind(this,"name4")} />
                <input type="text" onChange={this.showVal.bind(this,"name5")} />
                <input type="text" onChange={this.showVal.bind(this,"name6")} />
            </div>
        )
    }
}

方法2

使用ref去获取dom节点内的值

import React,{useRef} from 'react'
export default class form_input extends React.Component{
    constructor(){
        super()
        this.usname = useRef()
        this.age = useRef()
    }
    // 获取input DOM节点
    sbmmt(){
        console.log(this.usname.current.value)
        console.log(this.age.current.value)
    }
    render(){
        return(
            <div>
                <hr/>
                  {/*获取input dom 节点  */}
                  <input type="text" ref={this.usname}></input>
                  <input type="text" ref={this.age}></input>
                  <button onClick={this.sbmmt.bind(this)}>提交信息</button>
            </div>
        
            
        )
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值