【问题标题】:React/ReactNative static property in function component功能组件中的 React/ReactNative 静态属性
【发布时间】: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'

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

【问题讨论】:

标签: reactjs react-native react-navigation


【解决方案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 时让编辑器抱怨。 :(
猜你喜欢
  • 2020-01-02
  • 1970-01-01
  • 2021-01-08
  • 2020-01-04
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 2019-03-24
  • 2019-12-08
相关资源
最近更新 更多