【问题标题】:React native with typescript passing useState as props使用 typescript 传递 useState 作为 props 反应原生
【发布时间】:2020-12-21 13:28:27
【问题描述】:

我有 responsive.tsx 文件,我想将一个 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'
      },[])

【问题讨论】:

  • 请指定“类型问题”,但不要在代码 cmets 中。它会更具可读性。
  • 感谢您的建议。你能帮我吗?

标签: typescript react-native types


【解决方案1】:

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

要么将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;

点心:https://snack.expo.io/IMFVdOlK7

【讨论】:

  • 如何使用道具定义。喜欢 setOrientation:Props
  • 您对我的回答进行了哪些代码更改,第一次还是第二次?一旦你回复我会更新我的答案。
  • @OğulcanKarayel 我已经用我建议的解决方案编辑了我的答案,以实现您获得方向的总体目标。 react-native 包含一个 useWindowDimensions 钩子,让一切变得更容易。
  • 是的,我曾想过使用钩子,但我有包含字体大小等的主题文件,我正在使用来自 responsive.tsx 文件的 withWidthDp('5%') 。我根据方向更新宽度和高度。所以我不知道如何将钩子与主题一起使用。
  • @OğulcanKarayel 如果你能提供一个零食的例子,我可以更好地帮助你。
猜你喜欢
  • 2021-08-20
  • 2019-08-11
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2021-04-07
相关资源
最近更新 更多