Content provider: Jinniu District Wudi Software Development Studio
In react development, we sometimes encounter requirements that require us to manipulate the DOM, so we can attach a ref attribute to the component, and then call its methods or properties from the ref.
Let’s look at how both function components and class components mount the ref and use it:
Functional components (hooks) :
// React and useRef are introduced
import React, { useRef } from 'react; Function Content() {const fileInputEl = useRef(null); Return (<> {/* Mount ref */} file'} hidden / > {/ * use ref * /} {/ * when click this div triggers the click event of input * /} < div onClick = {() = > fileInputEl. Current. Click ()} > upload files < / div > } < / a >)Copy the code
Class components are created using ref
/ / introduction of the React
import React, { Component } from 'react';
export default class Content extends Component {
constructor(props) {
super(props);
// Create a ref with react.createref () and mount it to the component
this.editTableEl = React.createRef();
}
componentWillReceiveProps() {
/ / when triggered when the ref into componentWillReceiveProps lifecycle is mounted to the components of refreshDataSource () method (PS: this method is defined in the component mount ref)
this.editTableEl.current && this.editTableEl.current.refreshDataSource();
}
render() {
return (
<div>
<EditableTable/ / a mountref
ref={this.editTableEl}
/>
</div>)}}Copy the code