首页 > 解决方案 > 使用 typescript 传递 useState 作为 props 反应原生

问题描述

我有 responsive.tsx 文件,我想将一个 useState 挂钩作为道具,其中包含来自 app.tsx 的应用程序的方向模式。我对类型有疑问。

“Dispatch<SetStateAction>”类型的参数不可分配给“Props”类型的参数。“Dispatch<SetStateAction>”类型中缺少属性“setOrientation”,但在“Props”类型中是必需的

 //in responsive.tsx

type OrientationProp = {
    orientation:string
}
type Dispatcher<S> = Dispatch<SetStateAction<S>>;
type Props = {
    setOrientation : Dispatcher<any>
}
const listenOrientationChange = ({ setOrientation  }:Props) => {
  Dimensions.addEventListener("change", (newDimensions) => {
    // Retrieve and save new dimensions
    screenWidth = newDimensions.window.width;
    screenHeight = newDimensions.window.height;

    // Trigger screen's rerender with a state update of the orientation variable
  });

  let orientation:OrientationProp = {
    orientation: screenWidth < screenHeight ? "portrait" : "landscape",
  };
  setOrientation(orientation);
};





//in app.tsx
    const [orientation,setOrientation] = useState(null);
    
    
      useEffect(() => {
    
        listenOrientationChange(setOrientation) // the error is here //Argument of type 'Dispatch<SetStateAction<null>>' is not assignable to parameter of type 'Props'. Property 'setOrientation' is missing in type 'Dispatch<SetStateAction<null>>' but required in type 'Props'
      },[])

标签: typescriptreact-nativetypes

解决方案


您已声明listenOrientationChange接受具有setOrientation属性的对象,但您setOrientation直接传递了 setter。

要么将声明更改listenOrientationChange为:

const listenOrientationChange = (setOrientation: Dispatcher<any>) => { ... }

或在对象中传递setOrientationsetter:

useEffect(() => {
  listenOrientationChange({ setOrientation });
},[])

编辑:这是我将如何实现您正在尝试做的事情:

// App.tsx
import * as React from 'react';
import { Text, useWindowDimensions } from 'react-native';

type Orientation = 'portrait' | 'landscape';

const useOrientation = (): Orientation => {
  const {width, height} = useWindowDimensions();
  return width < height ? 'portrait' : 'landscape';
}

const App = () => {
  const orientation = useOrientation();
  return <Text>Orientation is {orientation}</Text>
};

export default App;

小吃在这里:https ://snack.expo.io/IMFVdOlK7


推荐阅读