如何转发 ref 函数声明而不是箭头函数?

Joh*_*ton 6 javascript reactjs

这是 React 网站上的示例:


const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

Run Code Online (Sandbox Code Playgroud)

我怎样才能做同样的事function(){}?我想这样做是因为我想避免创建匿名函数来帮助调试。

Pra*_*apa 9

您可以将 React 函数组件传递给React.forwardRef

function Button(props, ref) {
  return (
     <button ref={ref} className="FancyButton">
       {props.children}
     </button>
  )
}

const FancyButton = React.forwardRef(Button);
Run Code Online (Sandbox Code Playgroud)