refs and the dom

ref的使用:

ref使用方式一: 已废弃了

<input type="text" ref="item" />

获取DOM元素:this.refs.item.value

import React, {
    
     Component } from 'react'

export default class App extends Component {
    
    
    constructor() {
    
    
        super();
        this.state = {
    
    
        }
    }
    _dealClick(){
    
    
        // 获取DOM元素  过时了
        // console.dir(this.refs.item.value);

        console.dir(this.refs['item'].value);
    }
    render() {
    
    
        return (
           <div>
               <input type="text" ref="item" />
               <button onClick={
    
     ()=>this._dealClick() }>获取输入框中的内容</button>
           </div>
        )
    }
}

ref使用方式二:

<input type="text" ref={ (input)=>{
    this.input = input;
} } />

获取DOM元素:this.input.value

import React, {
    
     Component } from 'react'

export default class App extends Component {
    
    
    constructor() {
    
    
        super();
        this.state = {
    
    
        }
    }
    _dealClick(){
    
    
        console.log(this.input.value);
    }
    render() {
    
    
        return (
           <div>
               {
    
    /* 形参input表示当前的真实DOM元素 */}
               <input type="text" ref={
    
     (input)=>{
    
    
                    this.input = input;
               } } />
               <button onClick={
    
     ()=>this._dealClick() }>获取输入框中的内容</button>
           </div>
        )
    }
}

ref使用方式三:
1) this.ref1 = React.createRef(); // 创建一个ref
2)<input type=“text” ref={ this.ref1 } />
3)获取DOM元素:this.ref1.current.value

import React, {
    
     Component } from 'react'

export default class App extends Component {
    
    
    constructor() {
    
    
        super();
        this.ref1 = React.createRef(); // 创建一个ref
    }
    _dealClick(){
    
    
        // console.dir(this.ref1.current);  // this.ref1.current获取DOM元素
        console.dir(this.ref1.current.value); 
        
    }
    render() {
    
    
        return (
           <div>
               <input type="text" ref={
    
     this.ref1 } />
               <button onClick={
    
     ()=>this._dealClick() }>获取输入框中的内容</button>
           </div>
        )
    }
}

ref和表单处理:

受控表单和非受控表单:

这里所谓受控是指受状态的控制。

<input type="text" />默认情况下,一个普通的input框,它是不受控的。
一个非受控的表单,要写获取表单中的数据,可以使用ref。

我们可以让表单中的数据和组件中的状态相关联。也就是说状态变了,表单中的数据也要发生改变。

猜你喜欢

转载自blog.csdn.net/QZ9420/article/details/112466163