参考:https://segmentfault.com/a/1190000012404114
两种方法,受控组件和非受控组件。
推荐使用受控组件,即通过this.state获取,因为其符合react规范;
受控组件示例,将文本框中字母转为大写
<input type="text" value={this.state.value} onChange={(e) => { this.setState({ value: e.target.value.toUpperCase(), }); }} />
也可以使用非受控组件,即给标签指定ref属性:
import React, { Component } from 'react'; class UnControlled extends Component { handleSubmit = (e) => { console.log(e); e.preventDefault(); console.log(this.name.value); } render() { return ( <form onSubmit={this.handleSubmit}> <input type="text" ref={i => this.name = i} defaultValue="BeiJing" /> <button type="submit">Submit</button> </form> ); } } export default UnControlled;