表单元素的value
/checked
值与state绑定,同时表单元素的onChange可以动态的改变对应的state的值,即数据的变更可以更新视图,用户操作视图的更新也可以触发state数据的更新.
import React from 'react'; class FormDemo extends React.Component { state = { username: '', password: '' } handleChange = event => { const { name, value } = event.target; this.setState({ [name]: value, }); } onSubmit = () => { const { username, password } = this.state; console.log({ username, password, }) } render () { const { username, password } = this.state; return ( <div className="form"> <p> <span>用户名:</span> <input value={username} name="username" onChange={this.handleChange} /> </p> <p> <span>密码:</span> <input value={password} name="password" onChange={this.handleChange} /> </p> <button onClick={this.onSubmit}>登录</button> </div> ) } } export default FormDemo;
我是歌谣,欢迎和大家一起交流前后端知识。放弃很容易,
但坚持一定很酷。欢迎大家一起讨论
与歌谣一起通关前端面试题