You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:18:08