1.通过 onChange -- e.target.value
class App extends Component { state = { username: '张三' }; // 用户名 getUserName(e){ console.log(e.target.value); this.setState({ username: e.target.value }); console.log(this.state.username); // setState为异步,存在延迟 } render() { return ( <div> <input type="text" onChange={this.getUserName.bind(this)} /> </div> ); } }
2.通过 ref -- this.refs.name
/** * ref 用于对DOM进行操作,不建议频繁使用 */ import React, { Component } from 'react'; // 创建类 class HelloMessage extends Component { handleClick(){ this.refs.myText.focus(); console.log(this.refs.myText.value); } render(){ return ( <div> <input type="text" ref="myText" /> <button onClick={() => this.handleClick()}>click</button> </div> ); } } // 通过继承的方式创建类 class App extends Component { render() { return ( <HelloMessage /> ); } } export default App;
或
/** * ref 回调 */ import React, { Component } from 'react'; // 创建类 class HelloMessage extends Component { handleClick(){ this.myText.focus(); console.log(this.myText.value); } render(){ return ( <div> <input type="text" ref={(dom) => {this.myText = dom}} /> <button onClick={() => this.handleClick()}>click</button> </div> ); } } // 通过继承的方式创建类 class App extends Component { render() { return ( <HelloMessage /> ); } } export default App;
.