简体   繁体   English

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

[英]How to forward ref a function declaration instead of arrow function?

This is the example in React's website:这是 React 网站中的示例:


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

How can I do the same with function(){} ?我怎样才能对function(){}做同样的事情? I want to do this because I want to avoid create an anonymous function to help with debugging.我想这样做是因为我想避免创建一个匿名函数来帮助调试。

You could pass a React functional component to the argument of React.forwardRef您可以将 React 功能组件传递给React.forwardRef的参数

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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