受控组件和非受控组件

2020-07-23  本文已影响0人  栗子daisy

受控组件:

 constructor(props) {
        super(props)
        this.state = {
            value: ''
        }
    }
 changeValue = (event)=>{
        console.log(event.target.value)
        this.setState({
            value: event.target.value // 想双向绑定,改变输入框中的值时必须使用this.setState的方式
        })
    }
<input type="text" value={this.state.value} onChange={this.changeValue} /> 

非受控组件-使用ref
ref第一种写法:

 constructor(props) {
        super(props)
 // 需要在构造器中调用后才可以获取到该节点的值(非受控组件)
        this.username = React.createRef()
    }
 <input type="text" ref={this.username}/> 
this.username.current.value

ref第二种写法: String Ref(已过时,会被移除)
还有另一种设置 refs 的方法,但它被认为是过时的,可能很快就会被弃用。但是你可能会在其他人的代码中看到它,所以这里说一下。

<input type="text" ref="username" /> // 非受控组件取值的第二种方式
this.refs.username.value

antd里面的ref (console.log(this.XXX)可查看数据)
不过antd建议用受控组件

 constructor(props) {
        super(props)
     this.input1 = React.createRef()
    this.input2 = React.createRef()
    }
<Input ref={this.input1}/>
this.input1.input.value 或 this.input1.state.value
<Input.TextArea ref={this.input2}/>
this.input2.textAreaRef.value

https://www.jianshu.com/p/6ab081248989https://www.cnblogs.com/BillyYoung/p/10973540.html
https://imweb.io/topic/5b6136a06025939b125f45ff

上一篇 下一篇

猜你喜欢

热点阅读