最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to forward ref a function declaration instead of arrow function? - Stack Overflow

programmeradmin5浏览0评论

This is the example in React's website:


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

How can I do the same with function(){}? I want to do this because I want to avoid create an anonymous function to help with debugging.

This is the example in React's website:


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

How can I do the same with function(){}? I want to do this because I want to avoid create an anonymous function to help with debugging.

Share Improve this question asked Nov 5, 2020 at 4:08 John WinstonJohn Winston 1,4711 gold badge22 silver badges41 bronze badges 1
  • 1 Just declare your function like you normally would and pass it to forwardRef instead of the inline arrow function. – ray Commented Nov 5, 2020 at 4:11
Add a ment  | 

2 Answers 2

Reset to default 10

You could pass a React functional ponent to the argument of React.forwardRef

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

const FancyButton = React.forwardRef(Button);

You could also do something like this.

const FancyButton = React.forwardRef(function FancyButton(props, ref) {
  const {children} = props
  return (
    <button ref={ref} className="FancyButton">
      {children}
    </button>
  )
})
export default FancyButton
发布评论

评论列表(0)

  1. 暂无评论