- 受控组件
- 非受控组件
- 受控组件依赖于form表单自身,每个事件都要追踪,与state绑定
import React from 'react'
export default class FormDemo extends React.Component{
constructor(props) {
super(props)
this.state={
val: ''
}
}
handleChange = (e) => {
this.setState({
val: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault()
console.log(this.state.val)
}
render () {
return (
<div>
<form onSubmit={ this.handleSubmit }>
<input type="text" value={this.state.val} onChange={this.handleChange}/>
{/* <input type='submit' value='提交'></input> */}
<button type='submit'>提交</button>
</form>
</div>
)
}
}
- 非受控组件 (ref) 获取 dom形式
在current属性中
// 使用
export default class RefsDom extends React.Componnet {
construbtor() {
super()
// 第一步定义
this.helloDiv = React.createRef()
}
componentDidMound() {
this.helloDiv.current.style.color = 'red'
}
render() {
return (
<div>
<div ref={ this.helloDiv }>hello</div>
</div>
)
}
}
获取input dom
import React from 'react'
export default class RefsForm extends React.Component {
constructor() {
super()
this.refInput = React.createRef()
this.refPas = React.createRef()
}
getVal = () => {
console.log(this.refInput.current.value)
console.log(this.refPas.current.value)
}
render() {
return (
<div>
<input type="text" ref={ this.refInput }/>
<input type="password" ref={ this.refPas }/>
<button onClick={ this.getVal }>获取</button>
</div>
)
}
}