React Native调用setNativeProps报错:类型'never'无该属性
解决React Native中setNativeProps报"Property does not exist on type 'never'"的问题
问题原因
你代码里的useRef初始值为null,TypeScript无法自动推断出current属性的具体类型,默认将其判定为never类型,因此识别不到setNativeProps方法。
具体解决方法
指定明确的组件类型(推荐)
如果你的ref是绑定到TextInput、View这类原生组件,直接给useRef声明对应的类型即可:import { TextInput, useRef, useEffect } from 'react-native'; // 明确ref的类型为目标组件|null const inputElementRef = useRef<TextInput>(null); useEffect(() => { if (inputElementRef.current !== null) { inputElementRef.current.setNativeProps({ style: { fontFamily: fonts.REGULAR }, }); } }, []);这样TypeScript就能准确识别
current的类型,不会再出现类型报错。自定义类型声明(适用于自定义组件)
如果是支持setNativeProps的自定义组件,可以手动声明对应类型:// 定义包含setNativeProps的类型 type NativePropsComponent = { setNativeProps: (props: { style?: any }) => void; }; const inputElementRef = useRef<NativePropsComponent>(null);临时类型断言(仅应急使用)
不想修改ref声明的话,也可以在调用时强制断言类型:useEffect(() => { if (inputElementRef.current !== null) { (inputElementRef.current as TextInput).setNativeProps({ style: { fontFamily: fonts.REGULAR }, }); } }, []);
内容的提问来源于stack exchange,提问作者Bomber
相关产品推荐
相关产品推荐

