简体   繁体   中英

How to add ref to button in a HOC

https://codesandbox.io/s/agitated-field-uctfd?file=/src/App.js

I have a component that returns a button:

const Button = props => <button ref={?} style={{ color: props.color }}>bt</button>;

I am trying to understand HOCs and refForwarding. This is a HOC a Component:

const colorer = Button => {
  const ButtontWithRef = React.forwardRef((props, ref) => {
    return <Button {...props} ref={ref} />;
  });
  class Colored extends React.Component {
    render() {
      return <ButtonWithRef color="red" ref={this.props.passedRef} />;
    }
  }
  return Colored;
};

The colored button that is used in components:

const Colored = colorer(Button);

I am trying to access the button inside Button component using ref . But I don't know how to forward ref when the Button is passed through a HOC( colorer ). When I console.log the ref I get

Object {current: null}

App.js:

export default function App() {
  const myRef = React.createRef();
  console.log(myRef);
  return (<Colored passedRef={myRef} />);
}

How do I set the ref to the actual button inside Button ?

The button component can make use of forwardRef and pass on the ref to the actual button component

const Button = React.forwardRef(
      (props, ref) => <button ref={ref} style={{ color: props.color }}>bt</button>
);

The rest of the code will remain the same except inside App component you would make use of useRef instead of React.createRef since App is a functional component

const colorer = Button => {
  const ButtontWithRef = React.forwardRef((props, ref) => {
    return <Button {...props} ref={ref} />;
  });
  class Colored extends React.Component {
    render() {
      return <ButtonWithRef color="red" ref={this.props.passedRef} />;
    }
  }
  return Colored;
};

...
export default function App() {
  const myRef = useRef(null);
  console.log(myRef);
  return (<Colored passedRef={myRef} />);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM