受控:为了获取到表单元素的值,但不是通过dom操作 (双向数据绑定)
import React, { Component } from 'react';
class Forms extends Component {
constructor(){
super()
this.state = {
username:'zhangsan',
password:''
}
}
handleChange = e => {
// console.log(e.target.name)
// console.log(e.target.value)
this.setState({
// username:e.target.value
// http://es6.ruanyifeng.com/#docs/object#%E5%B1%9E%E6%80%A7%E5%90%8D%E8%A1%A8%E8%BE%BE%E5%BC%8F
[e.target.name]:e.target.value ----------对象的属性动态设置 (此处需要给每个表单元素设置name属性)
})
}
// handleChange2 = e => {
// this.setState({
// password:e.target.value
// })
// }
handleSubmit = (e) => {
// 拿到input的值
e.preventDefault() --------阻止表单默认事件
console.log(this.state)
// console.log("1111111111",document.getElementById('usernameId').value) -----------不建议操作dom
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label htmlFor="">
用户名:
<input value={this.state.username} name="username" onChange={this.handleChange} type="text"/>
</label>
<br/>
<label htmlFor="">
密码:
<input value={this.state.password} name="password" onChange={this.handleChange} type="password"/>
</label>
<br/>
<input type="submit" value="登录"/>
</form>
</div>
);
}
}
export default Forms;
在React中,如果我们要操作Dom,我们推荐使用非受控的方式 Ref
应用场景:input 获取焦点
获取input = file 的文件内容
import React, { Component } from 'react'
export default class Refs extends Component {
constructor(){
super()
this.fileRef = React.createRef() ----------------------------第二种方式
}
componentDidMount(){
console.log(this.refs.inputRef)
this.refs.inputRef.focus() -----------------------第一种方式
}
upload = () => {
// console.log(this.fileRef.current)
const file = this.fileRef.current.files[0]
console.log(file)
}
render() {
return (
<div>
<input id="testId" ref="inputRef" type="text"/><br/>
<input ref={this.fileRef} type="file"/><br/>
<button onClick={this.upload}>上传文件</button>
</div>
)
}
}