在 tsx 中使用 react 的 ref 属性

函数组件

const myRef = React.useRef<HTMLDivElement>(null);
return <div ref={myRef} />;

参考:1
参考:2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 `React.forwardRef` 包装组件时,可以通过 `React.forwardRef` 函数的第二个参数来获取传递给组件的 `ref`。在组件,需要使用 `React.useImperativeHandle` 函数来定义可暴露给父组件的属性和方法。这些属性和方法将绑定到传递给组件的 `ref` 上。 例如,假设我们有一个 `MyComponent` 组件,它使用了 `React.forwardRef`,我们想要将传递给 `MyComponent` 的 `ref` 绑定到 `input` 元素上,可以这样实现: ```tsx import React from 'react'; interface MyComponentProps { // ... } interface MyComponentRef { // ... } const MyComponent = React.forwardRef<MyComponentRef, MyComponentProps>((props, ref) => { const inputRef = React.useRef<HTMLInputElement>(null); React.useImperativeHandle(ref, () => ({ focus() { inputRef.current?.focus(); }, // ... })); return ( <div> <input ref={inputRef} /> {/* ... */} </div> ); }); export default MyComponent; ``` 在这个例子,`MyComponent` 组件包装了一个 `input` 元素,并使用 `useRef` 创建了一个 `inputRef` 对象,将其绑定到 `input` 元素上。使用 `useImperativeHandle`,将 `focus` 方法绑定到传递给组件的 `ref` 上。这样,外部就可以通过 `ref` 来调用 `focus` 方法。 使用组件时,需要使用 `React.createRef` 来创建一个 `ref` 对象,将其传递给 `MyComponent` 组件的 `ref` 属性。这样,`ref` 就可以正确地绑定到 `input` 元素上了。 ```tsx import React from 'react'; import MyComponent from './MyComponent'; function App() { const myComponentRef = React.createRef<MyComponentRef>(); function handleClick() { myComponentRef.current?.focus(); } return ( <div> <MyComponent ref={myComponentRef} /> <button onClick={handleClick}>Focus Input</button> </div> ); } export default App; ``` 这样就能正确地获取 `ref` 了,同时可以通过 `ref` 调用 `focus` 方法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值