Ref Introduction
This is provided by Reactref
The attribute is represented as a reference to the real instance of the component, which is actuallyComponent instance returned by ()
;It needs to be distinguished,()
When rendering a component, the component instance is returned; when rendering a dom element, the return is a specific dom node.
For example, the following code:
const domCom = <button type="button">button</button>; const refDom = (domCom,container); //ConfirmPass component content is omittedconst refCom = (<ConfirmPass/>,container); (refDom); (refCom);
1. Ref in string form
import React, { Component } from 'react' export default class index extends Component { showData = () => { // Get the input node const { inputRef } = // Output input value (); } render() { return ( <div> <input ref="inputRef" type="text" placeholder="Click the button to prompt data"/>&nbsp; <button onClick={ }>Click me to enter the value of the box</button> </div> ) } }
2. Ref in create form
import React, { Component } from 'react' export default class index extends Component { // After the call, return a container, storing the nodes identified by ref, and use them in a single way. In other words, if a ref is not defined, it must be called once. inputRef = () showData = () => { const refVal = (); } render() { return ( <div> <input ref={ } type="text" placeholder="Click the button to prompt data"/>&nbsp; <button onClick={ }>Click me to enter the value of the box</button> </div> ) } }
3. Ref in the form of callback function
import React, { Component } from 'react' export default class index extends Component { showData = () => { const { inputRef } = this (); } render() { return ( <div> {/* Pass a callback function here */} <input ref={ currentNode => = currentNode } type="text" placeholder="Click the button to prompt data"/>&nbsp; <button onClick={ }>Click me to enter the value of the box</button> </div> ) } }
Summarize:
The above three forms have their own advantages and disadvantages. It is more convenient and complicated to write Method 1 and Method 2. The method 3 passes a callback function, which not only simplifies the operation but also makes the code look more elegant. However, in the latest and later versions, React officially uses functional programming, so it is more recommended to use it.create
form ref.
This is the end of this article about the use of ref attributes in React. For more related content on the use of ref attributes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!