React.forwardRef

本文介绍了React的forwardRef和useImperativeHandle这两个高级特性,它们允许开发者在不直接操作子组件的情况下,传递和自定义ref。通过示例展示了如何使用useImperativeHandle来定制父组件通过ref访问的实例方法,以及不使用此Hook时的常规代码实现。理解并正确使用这些技术,能够帮助优化组件间的交互和提高代码的可维护性。
摘要由CSDN通过智能技术生成
  • React.forwardRef 允许某些组件接收 ref(ref 是为了获取某个节点的实例),并将其向下传递给 子组件
  • React.forwardRef的API中ref必须指向dom元素而不是React组件

forwardRef 与 Hook useImperativeHandle

useImperativeHandle 在使用 ref 时可以自定义暴露给父组件的实例值。在大多数情况下,应当避免使用 ref 这样的命令式代码。useImperativeHandle 应当与 forwardRef一起使用:

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);

没使用Hook useImperativeHandle时的代码

const ForwardInput = React.forwardRef((props, ref) => (
  <input ref={ref} />
));

class TestComponent extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef(); // 创建 ref 存储 textRef DOM 元素
  }
  componentDidMount() {
    this.inputRef.current.value = 'forwardRef'    
  }
  render() {
    return ( // 可以直接获取到 ForwardInput input 的 ref:
      <ForwardInput ref={this.inputRef}>
    )
  }
}

相关链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值