refs
- 1. Understand
- 2. What are the ways to create refs?
-
- 2.1. String Refs (not recommended)
- 2.2. Callback Refs
- 2.3. React.createRef() (recommended)
- 2.4. Through React Hook (functional component)
- 3. Example
-
- 3.1. Focus management
- 3.2. Text selection
- 3.3. Media playback
- 3.4. Forced trigger animation
- 3.5. Inherit third-party DOM libraries
- Reference address
1. Understand
Refs are a mechanism in React for accessing DOM elements within a component or other React component instances. They provide a way for you to directly manipulate and access DOM elements in React, or communicate between React components.
use:
- Focus management, text selection, media playback;
- Force trigger animation;
- Inherit third-party DOM libraries;
2. What are the ways to create refs
2.1, String Refs (not recommended)
String Refs are a way to create Refs in React, but starting from React 16.3, it is no longer officially recommended because it has some potential problems, such as performance issues and maintainability issues. However, for the sake of completeness, I will show how to use string Refs, but please use them with caution.
In string Refs, you assign the Ref as a string, typically in componentDidMount
, and you can then get the reference by accessing this.refs
.
Here is an example:
import React, {<!-- --> Component } from 'react'; class MyComponent extends Component {<!-- --> componentDidMount() {<!-- --> // Assign Ref as string this.refs.myRefElement.focus(); } render() {<!-- --> return ( <div> <input ref="myRefElement" /> {<!-- -->/* Assign Ref to string */} </div> ); } } export default MyComponent;
In the above example, we assign the Ref to the input
element using the string "myRefElement"
and then pass it in componentDidMount
this.refs.myRefElement accesses the element and puts focus on it.
Although string Refs were valid in the past, they are no longer officially recommended because they have issues with:
-
Performance issue: String Refs need to maintain an additional mapping table inside React in order to find Ref by string name. This can cause performance issues, especially in components with a large number of Refs.
-
Maintainability: When working with string Refs, they are difficult to statically analyze and inspect, so it is prone to typos or Refs that cannot be found.
Therefore, it is recommended to use the React.createRef()
or useRef
hook to create Refs in modern React applications to improve performance and maintainability.
2.2. Callback Refs
Callback Refs are a way to create Refs in React components that can be used to access DOM elements or other component instances. This method was the main way to create Refs before React 16.3. Although after React 16.3, it is officially recommended to use the React.createRef()
or useRef
hook to create Refs, but Calling back Refs is still a valid approach.
Here is a detailed description of how to use callback Refs:
-
Create Refs: In the component, first define a variable to hold the Ref object, usually initialized to
null
in the constructor.class MyComponent extends React.Component {<!-- --> constructor(props) {<!-- --> super(props); this.myRef = null; } }
-
Assign Refs to elements or components: On the DOM element or component that needs to be referenced, use the
ref
attribute to set the Ref variable to the callback function.setMyRef = (element) => {<!-- --> this.myRef = element; } render() {<!-- --> return ( <div> <input ref={<!-- -->this.setMyRef} /> </div> ); }
Through this callback function,
this.myRef
will refer to the DOM element or component instance associated with it. -
Access Refs: Where you need to access Refs, you can use
this.myRef
to get the referenced element or component.componentDidMount() {<!-- --> if (this.myRef) {<!-- --> this.myRef.focus(); // Focus on the input box through Ref } }
The advantage of callback Refs is that they are available in earlier React versions and work well for accessing instances of DOM elements or subcomponents. However, with the update of React version, it is officially recommended to use React.createRef()
or useRef
hook because they have more advantages in performance and maintainability. When you need to create Refs in a modern React project, it’s often a better option to use the React.createRef()
(class components) or the useRef
hook (functional components).
2.3, React.createRef() (recommended)
In React 16.3 and later, you can create Refs using the built-in React.createRef() method. This is an officially recommended method.
Creating Refs is easy using the React.createRef()
method. Here is a specific example:
import React from 'react'; class MyComponent extends React.Component {<!-- --> constructor(props) {<!-- --> super(props); this.myRef = React.createRef(); // Create Ref object } componentDidMount() {<!-- --> //After the component is rendered, DOM elements can be accessed this.myRef.current.focus(); // Focus on the DOM element } render() {<!-- --> return ( <div> <input ref={<!-- -->this.myRef} /> {<!-- -->/* Assign Ref to input element */} <button onClick={<!-- -->this.focusInput}>Focus Input</button> </div> ); } focusInput = () => {<!-- --> //Access Ref in event handler this.myRef.current.focus(); }; } export default MyComponent;
In the above example, we first create a Ref object using React.createRef()
in the constructor, and then use ref on the
input
element The code> attribute assigns this Ref to the DOM element. In the componentDidMount
lifecycle method, we use this.myRef.current
to access the DOM element and focus on the input
. We also use Ref in a button’s click event handler to once again focus the input
.
This is the general process of creating and accessing Refs using React.createRef()
. This method is usually used to access and manipulate DOM elements, or reference instances of subcomponents.
2.4, through React Hook (functional component)
Creating Refs in functional components is also very simple using React Hook (useRef
hook). Here is a specific example:
import React, {<!-- --> useRef, useEffect } from 'react'; function MyComponent() {<!-- --> const myRef = useRef(null); // Create Ref object useEffect(() => {<!-- --> // After the component is rendered, DOM elements can be accessed myRef.current.focus(); // Focus on the DOM element }, []); const focusInput = () => {<!-- --> //Access Ref in event handler myRef.current.focus(); }; return ( <div> <input ref={<!-- -->myRef} /> {<!-- -->/* Assign Ref to input element */} <button onClick={<!-- -->focusInput}>Focus Input</button> </div> ); } export default MyComponent;
In the above example, we first create a Ref object using useRef(null)
. The argument to useRef()
is an initial value, usually set to null
because it doesn’t care about the actual value during initial rendering.
We then use the useEffect
hook to simulate the componentDidMount
lifecycle method, where we use myRef.current
to access the DOM element and focus on input
on. useEffect
accepts the second parameter, a dependency array, here an empty array, indicating that this effect will only be executed during the initial rendering of the component.
Finally, we use Ref again in a button’s click event handler to focus the focus on input
.
Use the useRef
hook to conveniently create and access Refs in functional components, as well as perform Refs-related operations without using class components. This method is available in React 16.8 and later versions.
3. Example
3.1, Focus Management
Here is a simple React example that demonstrates how to use Refs to manage focus by moving focus from one input box to another. This example includes a button that, when clicked, moves focus from one input box to another.
import React, {<!-- --> Component } from 'react'; class FocusManagementExample extends Component {<!-- --> constructor(props) {<!-- --> super(props); this.inputRef1 = React.createRef(); // Create Ref for Input 1 this.inputRef2 = React.createRef(); // Create Ref for Input 2 } moveFocus = () => {<!-- --> this.inputRef2.current.focus(); // Move focus to Input 2 }; render() {<!-- --> return ( <div> <input ref={<!-- -->this.inputRef1} placeholder="Input 1" /> <input ref={<!-- -->this.inputRef2} placeholder="Input 2" /> <button onClick={<!-- -->this.moveFocus}>Move Focus to Input 2</button> </div> ); } } export default FocusManagementExample;
In this example, we first create two Refs, this.inputRef1
and this.inputRef2
, which reference two input boxes respectively. Then, in the moveFocus
method, we use this.inputRef2.current.focus()
to move focus to the second input box. When the button is clicked, the moveFocus
method is called and the focus will move from input box 1 to input box 2.
3.2. Text selection
Below is a simple React example that demonstrates how to use Refs to implement text selection functionality. In this example, there is a text input box and a button that, when clicked, selects the text in the text input box.
import React, {<!-- --> Component } from 'react'; class TextSelectionExample extends Component {<!-- --> constructor(props) {<!-- --> super(props); this.inputRef = React.createRef(); // Create Ref for the text input } selectText = () => {<!-- --> if (this.inputRef.current) {<!-- --> this.inputRef.current.select(); // Select text in the text input box } }; render() {<!-- --> return ( <div> <input ref={<!-- -->this.inputRef} placeholder="Type some text" /> <button onClick={<!-- -->this.selectText}>Select Text</button> </div> ); } } export default TextSelectionExample;
In this example, we first create a Ref this.inputRef
and assign it to the input box. Then, we define the selectText
method, which uses this.inputRef.current.select()
to select the text in the text input box. When the button is clicked, the selectText
method is called and the text in the text input box will be selected.
3.3. Media playback
Here is an example of using React to create a simple media player. This example includes a play/pause button, an audio element, and some state management to control the playback state.
import React, {<!-- --> Component } from 'react'; class MediaPlayerExample extends Component {<!-- --> constructor(props) {<!-- --> super(props); this.audioRef = React.createRef(); // Create Ref for the audio element this.state = {<!-- --> isPlaying: false, }; } togglePlay = () => {<!-- --> const audio = this.audioRef.current; if (this.state.isPlaying) {<!-- --> audio.pause(); } else {<!-- --> audio.play(); } this.setState({<!-- --> isPlaying: !this.state.isPlaying }); }; render() {<!-- --> return ( <div> <audio ref={<!-- -->this.audioRef} controls> <source src="your-audio-file.mp3" type="audio/mpeg" /> Your browser does not support the audio element. </audio> <button onClick={<!-- -->this.togglePlay}> {<!-- -->this.state.isPlaying ? 'Pause' : 'Play'} </button> </div> ); } } export default MediaPlayerExample;
In this example, we first create a Ref this.audioRef
and assign it to the audio
element. We then define the togglePlay
method, which plays or pauses the audio based on the current playback state (isPlaying
) and then updates the state to reflect the new playback state.
The element is used to play audio files and has controls to control playback. You can specify the URL of the audio file in the
src
attribute of the element.
The button element allows the user to click to toggle the play/pause state and displays the current state on the button.
This is a simple media player example, you can extend it to add more functions according to your actual needs, such as volume control, skip, loop, etc.
3.4. Forced trigger animation
In React, you can use ref
to access a component or DOM element to force an animation when needed. Here’s a simple example of how to force a CSS animation using React and ref
:
import React, {<!-- --> Component } from 'react'; class AnimationExample extends Component {<!-- --> constructor(props) {<!-- --> super(props); this.animationBoxRef = React.createRef(); // Create Ref for the animated box } startAnimation = () => {<!-- --> const box = this.animationBoxRef.current; //Add CSS class to trigger animation box.classList.add('animate'); // After the animation completes, remove the CSS class to reset the animation box.addEventListener('animationend', () => {<!-- --> box.classList.remove('animate'); }); }; render() {<!-- --> return ( <div> <div ref={<!-- -->this.animationBoxRef} className="box" ></div> <button onClick={<!-- -->this.startAnimation}>Start Animation</button> </div> ); } } export default AnimationExample;
In this example, we first create a Ref this.animationBoxRef
and assign it to a div
element that represents the animation. Target. Then, we define the startAnimation
method, which uses classList
to add a CSS class animate
to the div
element, to trigger the animation.
After the animation ends, we listen to the animationend
event using addEventListener
and remove the CSS class animate
in the event handler to reset the animation state.
Button elements allow users to click to trigger animations. You can define corresponding animation effects in CSS, such as through the @keyframes
rule to define the details of the animation.
3.5. Inherit third-party DOM libraries
Inheriting a third-party DOM library usually requires using ref
in React to access and manipulate DOM elements in the third-party library. The following is an example that demonstrates how to inherit a third-party DOM library in React (here, we use the D3.js library as an example):
First, make sure the D3.js library has been introduced into your project. You can add it to your project using npm or via the tag.
import React, {<!-- --> Component } from 'react'; import * as d3 from 'd3'; // Import D3.js class D3IntegrationExample extends Component {<!-- --> constructor(props) {<!-- --> super(props); this.svgRef = React.createRef(); // Create Ref for the SVG element } componentDidMount() {<!-- --> // After the component is mounted, initialize the D3.js operation const svg = d3.select(this.svgRef.current); // Add a rectangle to the SVG svg .append('rect') .attr('x', 10) .attr('y', 10) .attr('width', 100) .attr('height', 50) .style('fill', 'blue'); } render() {<!-- --> return ( <div> <svg ref={<!-- -->this.svgRef} width={<!-- -->200} height={<!-- -->100}></svg> </div> ); } } export default D3IntegrationExample;
In this example, we first introduce the D3.js library. We then create a Ref this.svgRef
and assign it to a element, which will be used to draw the D3.js graphics.
In the componentDidMount
life cycle method, we use the d3.select
method of D3.js to select the element and add A blue rectangle. You can perform more complex operations based on the D3.js documentation and needs.
This example demonstrates how to extend third-party DOM libraries in React, specifically D3.js. You can inherit other third-party libraries based on your project needs, and then use ref
to access and manipulate their DOM elements.
Reference address
chatgpt
https://zhuanlan.zhihu.com/p/549934728