https://zh-hans.reactjs.org/docs/refs-and-the-dom.html
字符串形式ref
1 <input ref="myinput" type="text" placeholder="字符串形式的ref" />
2 <button onClick={this.handleClick}>点击</button>
3
4 handleClick = () => {
5 console.log(this.refs.myinput.value);
6 };
回调函数形式ref
关于回调 refs 的说明:
如果 ref
回调函数是以内联函数的方式定义的,在更新过程中它会被执行两次,第一次传入参数 null
,然后第二次会传入参数 DOM 元素。这是因为在每次渲染时会创建一个新的函数实例,所以 React 清空旧的 ref 并且设置新的。通过将 ref 的回调函数定义成 class 的绑定函数的方式可以避免上述问题,但是大多数情况下它是无关紧要的
1 <input ref={(e) => {this.inputvalue = e; console.log(e)} } type="text" placeholder="回调函数形式的ref"/>
2 <button onClick={this.handleClick1}>点击</button>
3
4 handleClick1 = () => {
5 console.log(this.inputvalue.value);
6 };
<input ref={this.saveinput} type="text" placeholder="回调函数形式2的ref"/>
<button onClick={this.handleClick1}>点击</button> saveinput = (e) => {
this.inputvalue = e
}
handleClick1 = () => {
console.log(this.inputvalue.value);
};
React.createRef形式
1 myref = React.createRef() //createRef的ref
2 <input ref={this.myref} type="text" placeholder="createRef的ref"/>
3 <button onClick={this.handlechangerefs}>createRef的ref</button>
4
5 handlechangerefs = () => {
6 console.log(this.myref.current.value)
7 }