React Native实现BottomSheet时遇到Type 'string' is not assignable to type 'Ref<unknown> | undefined'错误,如何修复?
Fix: Type 'string' is not assignable to type 'Ref | undefined' in React Native BottomSheet
你遇到的这个错误根源在于使用了字符串类型的ref(ref="BottomSheet")——这种旧的ref写法已经被React官方废弃,而且TypeScript会严格校验ref的类型,所以才会抛出这个类型不匹配的错误。下面给你两种可靠的修复方案:
方案1:使用useRef钩子(推荐,适用于函数组件)
这是React当前推荐的ref使用方式,步骤很简单:
- 先从React中导入
useRef:
import { useRef } from 'react';
- 在组件内部创建一个ref对象:
const bottomSheetRef = useRef(null);
- 将这个ref对象传递给
BottomSheet组件:
<BottomSheet bottomSheerColor="#FFFFFF" ref={bottomSheetRef} // 替换原来的字符串ref initialPosition={'50%'} snapPoints={['50%', '100%']} isBackDrop={true} isBackDropDismissByPress={true} backDropColor="red" header={ <View> <Text style={styles.text}>Header</Text> </View> } body={ <View style={styles.body}> <Text style={styles.text}>Body</Text> </View> } />
之后你就可以通过bottomSheetRef.current来访问BottomSheet组件的实例,调用它的内部方法(比如展开/收起等)。
方案2:使用回调ref(适用于类组件或更灵活的场景)
如果你在类组件中开发,或者需要更灵活的ref控制逻辑,可以用回调ref的方式:
类组件示例:
class YourComponent extends React.Component { constructor(props) { super(props); this.bottomSheetRef = null; } render() { return ( <BottomSheet bottomSheerColor="#FFFFFF" ref={(ref) => { this.bottomSheetRef = ref; }} // 用回调函数获取ref initialPosition={'50%'} snapPoints={['50%', '100%']} isBackDrop={true} isBackDropDismissByPress={true} backDropColor="red" header={ <View> <Text style={styles.text}>Header</Text> </View> } body={ <View style={styles.body}> <Text style={styles.text}>Body</Text> </View> } /> ); } }
之后通过this.bottomSheetRef就能访问BottomSheet实例。
函数组件中使用回调ref:
如果在函数组件里想用回调ref,也可以用状态来保存:
import { useState } from 'react'; // 在组件内部 const [bottomSheetRef, setBottomSheetRef] = useState(null); // 传递给组件 <BottomSheet ref={(ref) => setBottomSheetRef(ref)} // 其他props... />
为什么字符串ref会报错?
字符串ref存在几个明显的问题:
- 类型系统不友好:TypeScript无法正确推断其类型,直接导致你遇到的类型错误
- 功能受限:无法在复杂逻辑中复用或动态控制ref
- 官方废弃:React已经不再推荐使用字符串ref,未来版本可能会移除相关支持
所以无论从类型安全还是长期维护的角度,都建议你换成上面两种现代的ref使用方式。
内容的提问来源于stack exchange,提问作者doğan kısa
相关产品推荐
相关产品推荐

