preface
The react component creates a ref by creating a literal, a callback, and a createRef. Creation with literals is common, but officially not recommended and may even be deprecated later. Let me introduce them one by one.
Literal creation
Creating it in a literal way is easier and requires only the following code
render(){
return (
<h1 ref = "h1"></h1>
<input ref = "input1" />)}Copy the code
Because there is a refs attribute on the instance, this.refs. So h1 and inpuT1, identified by ref, are collected in this.refs as {key:value}. Use this.refs.h1 to retrieve the h1 element in render.
Callback function creation (recommended)
render(){
return (
<input ref = {c= > this.input1 = c} />)}Copy the code
This means that the argument C is the current DOM element. And put it on the instance. When render is updated again, the callback function is called twice, the first time the DOM element is null, and the second time the DOM element is returned. React: / / React: / / react: / / react: / / React:
createRef = (c) = > {
// The required elements are in this parameter
}
render(){
return (
<input ref = {this.createRef} />)}Copy the code
CreateRef create
class Ref extends React.Component {
myRef = React.createRef()
myRef2 = React.createRef()
}
render() {
return (
<input ref = {this.myRef} />
<input ref = {this.myRef2} />)}Copy the code
The createRef() call returns a container containing the nodes identified by ref. Myref is on the instance object of the subclass, so the return in render can be identified by this.myref. In this method, you can call this.myref.current to get the DOM element.