programing tip

클래스 기반 컴포넌트에서 React.forwardRef를 사용하는 방법은 무엇입니까?

itbloger 2020. 10. 15. 07:36
반응형

클래스 기반 컴포넌트에서 React.forwardRef를 사용하는 방법은 무엇입니까?


React.forwardRef를 사용하려고하는데 HOC가 아닌 클래스 기반 구성 요소에서 작동하도록하는 방법에 대해 설명합니다.

문서 예제는 요소와 기능적 구성 요소를 사용하며 심지어 고차 구성 요소의 함수로 클래스를 래핑합니다.

그래서, 같은 것을 시작으로 자신의 ref.js파일을

const TextInput = React.forwardRef(
    (props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />)
);

대신 다음과 같이 정의합니다.

class TextInput extends React.Component {
  render() {
    let { props, ref } = React.forwardRef((props, ref) => ({ props, ref }));
    return <input type="text" placeholder="Hello World" ref={ref} />;
  }
}

또는

class TextInput extends React.Component {
  render() { 
    return (
      React.forwardRef((props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />))
    );
  }
}

만 작동 : /

또한, 알아요, 심판은 반응 방식이 아닙니다. 타사 캔버스 라이브러리를 사용하려고하는데 일부 도구를 별도의 구성 요소에 추가하려고하므로 이벤트 리스너가 필요하므로 수명주기 메서드가 필요합니다. 나중에 다른 경로로 갈 수 있지만 이것을 시도하고 싶습니다.

문서는 가능하다고 말합니다!

참조 전달은 DOM 구성 요소로 제한되지 않습니다. 참조를 클래스 구성 요소 인스턴스로 전달할 수도 있습니다.

이 섹션메모에서.

그러나 그들은 단지 수업 대신에 HOC를 사용합니다.


항상 동일한 prop을 사용하는 아이디어 ref는 도우미로 클래스 내보내기를 프록시하여 얻을 수 있습니다.

class ElemComponent extends Component {
  render() {
    return (
      <div ref={this.props.innerRef}>
        Div has ref
      </div>
    )
  }
}

export default React.forwardRef((props, ref) => <ElemComponent 
  innerRef={ref} {...props}
/>);

그래서 기본적으로, 우리는 ref를 전달하기 위해 다른 prop을 가져야하지만 허브 아래에서 할 수 있습니다. 대중이 일반 심판으로 사용하는 것이 중요합니다.


class BeautifulInput extends React.Component {
  const { innerRef, ...props } = this.props;
  render() (
    return (
      <div style={{backgroundColor: "blue"}}>
        <input ref={innerRef} {...props} />
      </div>
    )
  )
}

const BeautifulInputForwardingRef = React.forwardRef((props, ref) => (
  <BeautifulInput {...props} innerRef={ref}/>
));

const App = () => (
  <BeautifulInputForwardingRef ref={ref => ref && ref.focus()} />
)

ref를 클래스로 전달하려면 다른 prop 이름을 사용해야합니다. innerRef많은 라이브러리에서 일반적으로 사용됩니다.


기본적으로 이것은 단지 HOC 함수입니다. 클래스와 함께 사용하고 싶다면 혼자서 할 수 있고 일반 소품을 사용할 수 있습니다.

class TextInput extends React.Component {
    render() {
        <input ref={this.props.forwardRef} />
    }
}

const ref = React.createRef();
<TextInput forwardRef={ref} />

이 패턴은 예를 들어에서 사용되며 거기 styled-components에서 호출 innerRef됩니다.


This can be accomplished with a higher-order component, if you like:

import React, { forwardRef } from 'react'

const withForwardedRef = Comp => {
  const handle = (props, ref) =>
    <Comp {...props} forwardedRef={ref} />

  const name = Comp.displayName || Comp.name
  handle.displayName = `withForwardedRef(${name})`

  return forwardRef(handle)
}

export default withForwardedRef

And then in your component file:

class Boop extends React.Component {
  render() {
    const { forwardedRef } = this.props

    return (
      <div ref={forwardedRef} />
    )
  }
}

export default withForwardedRef(Boop)

I did the work upfront with tests & published a package for this, react-with-forwarded-ref: https://www.npmjs.com/package/react-with-forwarded-ref


Incase you need to reuse this in many difference components, you can export this ability to something like withForwardingRef

const withForwardingRef = <Props extends {[_: string]: any}>(BaseComponent: React.ReactType<Props>) =>
    React.forwardRef((props, ref) => <BaseComponent {...props} forwardedRef={ref} />);

export default withForwardingRef;

usage:

const Comp = ({forwardedRef}) => (
 <input ref={forwardedRef} />
)
const EnhanceComponent = withForwardingRef<Props>(Comp);  // Now Comp has a prop called forwardedRef

참고URL : https://stackoverflow.com/questions/51526461/how-to-use-react-forwardref-in-a-class-based-component

반응형