React useImperativeHandle

使用函数时组件的时候,ref转发是必须要了解的概念

// 实现 ref 的转发
const FancyInput = React.forwardRef((props, ref) => (
  <div>
    <input ref={ref} type="text" />
    <div>我是自定义的函数式组件</div>
  </div>
));

const App = () => {
  const ref = useRef();
  return (
    <div>
      <FancyInput ref={ref} />
      <button onClick={() => {ref.current.focus()}}>
        调用input的focus方法
      </button>
    </div>
  )
}

ReactDOM.render(<App />, root);

如上,简介明了的解释了ref转发的概念。
但是,上面的 ref 透传的方式有什么问题呢

  • 站在 FancyInput 组件的角度,FancyInput组件在中间层,父组件App 越过了自己,直接获取了自己的子组件 inputref,子组件的DOM直接暴露给了父组件

  • input 组件的所有方法都直接暴露给App,App组件可以进行任意的操作,某些情况的不可控

  • 我们只是希望App可以操作的inputfocus方法,并不希望它随意操作其他方法

useImperativeHandle 就是来解决这个问题的:

const FancyInput = React.forwardRef((props, ref) => {
  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    focus: () => {
      // 这里可以加自己的逻辑哦
      inputRef.current.focus();
    }
  }));

 return (
  <div>
    <input ref={inputRef} type="text" />
    <div>我是自定义的函数式组件</div>
  </div>
 )
});

const App = props => {
  const fancyInputRef = useRef();

  return (
    <div>
      <FancyInput ref={fancyInputRef} />
      <button onClick={() => {fancyInputRef.current.focus()}}>
        调用FancyInput组件的 focus方法
      </button>
    </div>
  )
}

ReactDOM.render(<App />, root);

使用 useImperativeHandle 后,FancyInput有自己的 ref,通过 React.forwardRef 将父组件的 ref 透传过来,通过 useImperativeHandle 方法来暴露指定的方法给父组件调用,完美的解决了上面的问题。你还可以自己在 input 的 focus 方法上加一些自己的逻辑或者副作用,是不是有点钩子的意味了。


注意: useImperativeHandle 和 React.forwardRef 必须是配合使用的。

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值