我有响应文件。我想使用useState钩子作为道具,其中包含app.tsx中应用程序的定向模式。我的类型有问题。
“ Dispatch
//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'
},[])
答案 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;