When working with DOM elements in React, it's common to encounter the need to select and operate on specific elements to manipulate the user interface. In this case, the goal is to update a progress bar component based on a user's selection.
To access DOM elements in React, we can utilize the concept of "refs." Refs provide a mechanism to create a reference to a particular element in the component tree, enabling direct access to its properties and methods.
In React 16.8 (Function Components):
// Define the ref for the child component const ChildRef = useRef(null); // Forward the ref to the child component with React.forwardRef() const Child = React.forwardRef((props, ref) => { // Receive and store the forwarded ref in useRef() ChildRef.current = ref; return <div>Child Component</div>; });
In React 16.3 (Class Components):
// Create a ref for the component instance this.myRef = React.createRef(); // Pass the ref to the element within the render method render() { return <div ref={this.myRef} />; }
Access the Referenced Element:
Once a ref is established, we can access the DOM element using:
const element = this.myRef.current;
With access to the desired element, you can now perform the required operation. In your case, you want to execute the addPrecent function to update the progress bar's completed percentage.
document.getElementById(this.state.baction).addPrecent(10);
Legacy methods for accessing DOM elements include using string refs or callback refs:
String Refs:
<Progressbar completed={25}>
Callback Refs:
<Progressbar completed={25}>
However, these methods are discouraged due to potential issues and are likely to be removed in future React versions.
By incorporating refs, you can effectively select and operate on specific DOM elements, enhancing your React application's interactivity and flexibility.
The above is the detailed content of How to Directly Manipulate Specific React Elements Using Refs?. For more information, please follow other related articles on the PHP Chinese website!