首页 > 解决方案 > 如何在 HOC 中将 ref 添加到按钮

问题描述

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

我有一个返回按钮的组件:

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

我正在尝试了解 HOC 和 refForwarding。这是一个 HOC 组件:

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;
};

组件中使用的彩色按钮:

const Colored = colorer(Button);

我正在button尝试Button使用ref. ref但是当Button通过 HOC( colorer)时,我不知道如何转发。当我 console.logref我得到

Object {current: null}

应用程序.js:

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

如何将其设置ref为实际的button内部Button

标签: javascriptreactjs

解决方案


按钮组件可以利用forwardRef并传递ref给实际的按钮组件

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

其余代码将保持不变,除了您将使用的 App 组件内部useRefReact.createRef因为 App 是一个功能组件

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} />);
}

推荐阅读