功能组件中的 React/ReactNative 静态属性

Posted

技术标签:

【中文标题】功能组件中的 React/ReactNative 静态属性【英文标题】:React/ReactNative static property in function component 【发布时间】:2019-12-15 16:44:51 【问题描述】:

在我的 React Native 编写的 TypeScript 中,我使用了 ReactNavigation。在我使用下面的类组件之前

class HomeScreen extends Component 
   static navigationOptions: any;
   ...


// in navigation config
HomeScreen.navigationOptions = ...

有了 hooks 支持,我将 HomeScreen 迁移到如下功能组件

function HomeScreen(props:Props) 
  return (...)

HomeScreen.navigationOptions = ... // VS Code error here

问题是我错过了static navigationOptions: anypropery/method,并得到了错误 [In VS Code]

'navigationOptions' 不存在于类型'(props: Props) => Element'

有没有办法在函数组件中拥有静态属性/方法?或者有什么解决方法?

【问题讨论】:

你的打字稿版本是什么? 我使用的是 TS v 3.3 reactandtypescript.dev/examples/…希望对您有所帮助! 【参考方案1】:

对于功能组件,可以这样使用

HomeScreen.navigationOptions = screenProps => (
    title: 'Home'
)

对于打字稿的支持

interface NavParams 
    id: number;

const HomeScreen: NavigationScreenComponent<NavParams> = (props: Props) => 
    return <View><Text>props.navigation.getParam('id')</Text></View>

HomeScreen.navigationOptions = screenProps => (
    title: 'Home'
)

【讨论】:

最新版本的 react-navigation 有什么更新吗?【参考方案2】:

这可能有点晚了。 你的功能组件就像

export default function HomeScreen(props)
  return(..)

//the following is the static field from class component
HomeScreen.navigationOptions=
 title:'Home',
;

我希望这可能对某人有所帮助。

【讨论】:

这对于 javascript 来说似乎没问题,但在使用 TypeScript 时让编辑器抱怨。 :(

以上是关于功能组件中的 React/ReactNative 静态属性的主要内容,如果未能解决你的问题,请参考以下文章