react如何处理多个input取值
我们有这样的需求,页面中有很多input需要取值,如果数量少的话,可以一个一个的定义,但是如果数据多起来的话一个一个的处理显得太傻了,并且工作量会很多,网上查了一下,可以这样来统一处理我们的input。
关键点就是我们传递一下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>
)
}
}
欢迎关注小程序,感谢您的支持!