[React] Forward a DOM reference to another Component using forwardRef in React 16.3
React to in Using dom Component reference another
2023-09-14 09:00:50 时间
The function forwardRef
allows us to extract a ref and pass it to its descendants. This is a powerful tool, but should be used with caution to avoid unexpected ref behaviour. The technique of forwarding refs really starts to shine in combination with higher order components (HOCs).
forwardRef should be used when you are using HOC and pasing the ref around from parent to child component.
parent component:
import React, { Component } from "react"; import TextInput from "./TextInput"; class App extends Component { inputRef = React.createRef(); focusInput = () => { this.inputRef.current.focus(); }; render() { return ( <React.Fragment> <TextInput inputRef={this.inputRef} /> <button onClick={this.focusInput}>Focus</button> </React.Fragment> ); } } export default App;
child commponent:
import React, { Component, Fragment } from "react"; import logProps from "./logProps"; class TextInput extends Component { render() { return <input ref={this.props.inputRef} />; } } export default logProps(TextInput);
HOC componnet:
import React, { Component } from "react"; function logProps(Component) { class LogProps extends Component { componentDidUpdate(prevProps) { console.log("before update", prevProps); console.log("after update", this.props); } render() { const { forwardRef, ...rest } = this.props; return <Component {...rest} ref={forwardRef} />; } } const forwardRef = (props, ref) => { return <LogProps forwardRef={ref} {...props} />; }; const name = Component.displayName || Component.name; forwardRef.displayName = `logProps(${name})`; return React.forwardRef(forwardRef); } export default logProps;
Display name:
Becasue HOC component doesn't have a correct display name in the dev tool, we need to set it up:
const forwardRef = (props, ref) => { return <LogProps forwardRef={ref} {...props} />; }; const name = Component.displayName || Component.name; forwardRef.displayName = `logProps(${name})`; return React.forwardRef(forwardRef);
相关文章
- 【华为云技术分享】三大前端技术(React,Vue,Angular)探密(上)
- [React] useImperativeHandle, similar to Angular Directive `exportAs`
- [React Recoil] Write a Custom Recoil Hook to Reset a Value in the Recoil State
- [React] Simplify and Convert a Traditional React Form to Formik
- [PWA] Add Push Notifications to a PWA with React in Chrome and on Android
- [React] Understanding setState in componentDidMount to Measure Elements Without Transient UI State
- [React] Use React Fragments to make your DOM tree cleaner
- [Recompose] Create Stream Behaviors to Push Props in React Components with mapPropsStream
- [React] Call setState with null to Avoid Triggering an Update in React 16
- []H5、React Native、Native应用对比分析
- [XState + React] using @xstate/inspect to display state machine char in webapp
- [Typescript + React] Tips: Write your own 'PropsFrom' helper to extract props from any React component
- [React Typescript 2022] Use TypeScript to Type a React Class Component
- [React] Use the React Context API to Globally Manage State
- [React] Use a lazy initializer with useState
- [React Recoil] Write a Custom Recoil Hook to Reset a Value in the Recoil State
- [PWA] Add Push Notifications to a PWA with React in Chrome and on Android
- [React] Refactor componentWillReceiveProps() to getDerivedStateFromProps() in React 16.3
- [React Router] Create a ProtectedRoute Component in React Router (setState callback to force update)
- [Recompose] Create Stream Behaviors to Push Props in React Components with mapPropsStream
- [Recompose] Merge RxJS Button Event Streams to Build a React Counter Component
- [Recompose] Pass a React Prop to a Stream in RxJS
- [React] Call setState with null to Avoid Triggering an Update in React 16
- [React Intl] Use a react-intl Higher Order Component to format messages
- [React Intl] Format a Date Relative to the Current Date Using react-intl FormattedRelative
- [React Router v4] Redirect to Another Page