通过传递useState作为道具的打字稿来进行本机反应

时间:2020-09-02 11:23:55

标签: typescript react-native types

我有响应文件。我想使用useState钩子作为道具,其中包含app.tsx中应用程序的定向模式。我的类型有问题。

“ Dispatch ”类型的参数不能分配给“ Props”类型的参数。类型'Dispatch '中缺少属性'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'
      },[])

1 个答案:

答案 0 :(得分:1)

您已声明listenOrientationChange接受具有setOrientation属性的对象,但是您正在直接传递setOrientation设置方法。

listenOrientationChange的声明更改为:

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

或在对象中传递setOrientation设置器:

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