簡體   English   中英

當它是一個功能組件時如何獲取孩子的參考

[英]How to get the ref of a children when its a functional component

我試圖創建一個 HOC 來獲取任何組件的ref

當我通過正常的 jsx 時,效果很好。 但是當我傳遞一個功能組件時它不起作用:

class GetRef extends React.Component {
  state = {};
  constructor(props) {
    super(props);
    this.renderChildren = this.renderChildren.bind(this);
  }
  componentDidMount() {
    this.props.setRef(this.ref);
  }

  renderChildren() {
    const childElement = React.Children.only(this.props.children);
    return React.cloneElement(childElement, { ref: (el) => (this.ref = el) });
  }

  render() {
    return <>{this.renderChildren()}</>;
  }
}

const RefRegister = ({ children }) => {
  const [ref, setRef] = useState();
  console.log({ ref });
  return <GetRef setRef={setRef}>{React.Children.only(children)}</GetRef>;
};

const Example = () => <div>example</div>;

export default function App() {
  return (
    <div className="App">
      <RefRegister>
        {/* <div>example</div> */} Works well in this case
        <Example /> // Throws an error passing a component :(
      </RefRegister>
    </div>
  );
}

演示

使用React.forwardRef

const Example = React.forwardRef((props, ref) => <div ref={ref}>example</div>);

演示 - https://codesandbox.io/s/practical-proskuriakova-ywdj6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM