input收集数据的四种方案
实现功能:页面中显示一个输入框及一个提交按钮,当点击提交按钮button时,后台获取到输入框中所输入的内容。
实现过程:
首先定义一个类组件,使类组件挂载到DOM节点上,在类组件的render中返回一个输入框及一个提交按钮,给按钮绑定一个点击事件,当点击按钮时,触发事件在后台打印出输入框中的内容,代码如下:
<script type="text/babel">
class Form extends React.Component{
constructor(){
super();
this.inputRef3=React.createRef()
}
handleClick=()=>{
//第一种
console.log(this.refs);
console.log(this.refs.inputRef1);
console.log(this.refs.inputRef1.value);
//第二种
console.log(this.inputRef2);
console.log(this.inputRef2.value);
//第三种
console.log(this.inputRef3);
console.log(this.inputRef3.current);
console.log(this.inputRef3.current.value);
}
render(){
return(
<div>
//第一种
<input type="text" ref='inputRef1'/>
<br/>
//第二种
<input type="text" ref={e=>this.inputRef2=e}/>
<br/>
//第三种
<input type="text" ref={this.inputRef3}/>
<br/>
<button onClick={this.handleClick}>提交</button>
</div>
)
}
}
ReactDOM.render(<Form />, document.getElementById("app"));
</script>
执行结果如下:
通过三种不同的方法,都可获取到输入框的返回值,第一种方法是通过操作 ' key ' 获取数值,第二种是通过 函数的属性 来获取数值,第三种是通过 容器属性 找到返回的数值。
此外,还可以通过监听事件(onChange)的方法获取到数值,通过事件绑定的方法将修改的数据同步渲染。
handleChange=(e)=>{
console.log("handleChange");
console.log(e.target.value);
}
render(){
return(
<div>
<input type="text" onChange={this.handleChange}/>
<br/>
<button onClick={this.handleClick}>提交</button>
</div>
)
}