1. 受控组件
    2. 非受控组件
    • 受控组件依赖于form表单自身,每个事件都要追踪,与state绑定
    1. import React from 'react'
    2. export default class FormDemo extends React.Component{
    3. constructor(props) {
    4. super(props)
    5. this.state={
    6. val: ''
    7. }
    8. }
    9. handleChange = (e) => {
    10. this.setState({
    11. val: e.target.value
    12. })
    13. }
    14. handleSubmit = (e) => {
    15. e.preventDefault()
    16. console.log(this.state.val)
    17. }
    18. render () {
    19. return (
    20. <div>
    21. <form onSubmit={ this.handleSubmit }>
    22. <input type="text" value={this.state.val} onChange={this.handleChange}/>
    23. {/* <input type='submit' value='提交'></input> */}
    24. <button type='submit'>提交</button>
    25. </form>
    26. </div>
    27. )
    28. }
    29. }
    • 非受控组件 (ref) 获取 dom形式
    • current属性中

      1. // 使用
      2. export default class RefsDom extends React.Componnet {
      3. construbtor() {
      4. super()
      5. // 第一步定义
      6. this.helloDiv = React.createRef()
      7. }
      8. componentDidMound() {
      9. this.helloDiv.current.style.color = 'red'
      10. }
      11. render() {
      12. return (
      13. <div>
      14. <div ref={ this.helloDiv }>hello</div>
      15. </div>
      16. )
      17. }
      18. }
    • 获取input dom

    1. import React from 'react'
    2. export default class RefsForm extends React.Component {
    3. constructor() {
    4. super()
    5. this.refInput = React.createRef()
    6. this.refPas = React.createRef()
    7. }
    8. getVal = () => {
    9. console.log(this.refInput.current.value)
    10. console.log(this.refPas.current.value)
    11. }
    12. render() {
    13. return (
    14. <div>
    15. <input type="text" ref={ this.refInput }/>
    16. <input type="password" ref={ this.refPas }/>
    17. <button onClick={ this.getVal }>获取</button>
    18. </div>
    19. )
    20. }
    21. }