typescript - 使用 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'
},[])
解决方案
您已声明listenOrientationChange
接受具有setOrientation
属性的对象,但您setOrientation
直接传递了 setter。
要么将声明更改listenOrientationChange
为:
const listenOrientationChange = (setOrientation: Dispatcher<any>) => { ... }
或在对象中传递setOrientation
setter:
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;
推荐阅读
- xamarin.forms - 在 iOS/Android 应用上使用 IdentityServer 进行生物识别登录
- flutter - Flutter 在多个列表之间拖放列表项
- mongodb - Veracode 中 Mongoose Create 的数据查询逻辑中特殊元素的中和不当
- google-apps-script - 如何使用 Appscript 从单元格中的层次结构中获取最后一个值?
- android - 以编程方式添加开关按钮拇指色调颜色(ANDROID STUDIO)
- angular - 谷歌选择器回调不能在角度工作
- mongodb - Inserting data in a dockerized mongodb on startup
- javascript - 如何设置 Material UI 抽屉的宽度
- jquery - KendoUI 下拉过滤器不适用于 jquery
- javascript - 我只想在 java 脚本中更改选项卡/窗口时设置时间间隔