为反应导航道具添加强类型

时间:2017-12-21 11:57:05

标签: typescript react-native react-navigation

我在react-native项目(expo)中使用typescript。

该项目使用反应导航,因此在我的屏幕上我可以设置$url = "http://45.116.113.98:8081/WebAP1/api/SchemeMast/1/40/WEBDTG100-/45/-/Prabakaran/S/-/4-44,pillaiyar%20kovil%20street,ko.thoppu%20vill,nochalu/-/Villupuram/Villupuram/Tamil%20Nadu/India/604201/9787162221/9787162221/0.000/100.00/2017-12-21/C"; $headers = array(); $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg'; $headers[] = 'Connection: Keep-Alive'; $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8'; $user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)'; $process = curl_init($url); curl_setopt($process, CURLOPT_HTTPHEADER, $headers); curl_setopt($process, CURLOPT_HEADER, 0); curl_setopt($process, CURLOPT_USERAGENT, $user_agent); curl_setopt($process, CURLOPT_RETURNTRANSFER, 1); curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1); $return = curl_exec($process); curl_close($process); 并且我可以访问道具 curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); curl_setopt( $ch, CURLOPT_HTTPGET, 1 ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION , 1 ); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

现在我正在尝试强类型这些,所以我得到了可用于设置的属性的提示。

navigationOptions

将反应导航作为组件的道具处理的最佳方法是什么。

11 个答案:

答案 0 :(得分:25)

只需将NavigationType添加到道具中,如下所示:

    import { StackNavigator, NavigationScreenProp } from 'react-navigation';

    export interface HomeScreenProps {
      navigation: NavigationScreenProp<any,any>
    };

    export class HomeScreen extends React.Component<HomeScreenProps, object> {

      render() {
        return (
          <View style={styles.container}>       
            <Button
              title="Go to Details"
              onPress={() => this.props.navigation.navigate('Details')}
            />
          </View>
        );
      }
    }

答案 1 :(得分:4)

这有效:

static navigationOptions = ({ navigation }: NavigationScreenProps) => ({
  ...
})

答案 2 :(得分:3)

我有同样的问题,这是我的解决方案:

<!DOCTYPE html>
<html>
<head>
    <title></title>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>

hello shubham

<div data-load="header.html"></div>


<script type="text/javascript">
    $(function(){
    $("[data-load]").each(function(){
        $(this).load($(this).data("load"), function(){
        });
    });
})
</script>

</body>


</html>

您可能希望将import * as React from 'react' import { NavigationScreenProps, NavigationStackScreenOptions } from 'react-navigation' interface NavStateParams { someValue: string } // tslint:disable-next-line:no-any type NavigationOptionsFn<TParams=any> = (props: NavigationScreenProps<TParams>) => NavigationStackScreenOptions class Screen extends React.Component { // This should works fine static navigationOptions: NavigationOptionsFn<NavStateParams> = ({ navigation, screenProps }) => ({ title: navigation.state.params.someValue }) } 类型声明为某个NavigationOptionsFn<TParams>文件,以使其在全球范围内有效。

答案 3 :(得分:2)

SELECT 
       SUM ([TotalQty]) AS 'Total',
       DATEPART (year,[Date]) AS 'Year',
       DATEPART (month,[Date]) AS 'Month',
       DATEPART (day,[Date]) AS 'Day'
FROM [dbo].[SalesMainTable]

where  DATEPART (year,[Date]) between @FromYear and @ToYear

GROUP BY DATEPART (year,[Date])
       ,DATEPART (month,[Date])
       ,DATEPART (day,[Date])

答案 4 :(得分:1)

public static navigationOptions: NavigationScreenConfig<NavigationStackScreenOptions> = 
    ({navigation}) => ({/* Your options... */})

答案 5 :(得分:1)

如果有人在扩展NavigationScreenProps时仍然遇到此问题,那么您可以正确键入navigationOptions等以及自己的道具:

interface Props extends NavigationScreenProps {
  someProp: string;
  anotherProp: string;
}

export const SomeGreatScreen: NavigationScreenComponent<NavigationParams, {}, Props> = ({
  someProp,
  anotherProp,
}) => {
...
};

NavigationScreenComponent<Props>导致结构化属性{ someProp, anotherProp }的类型错误,而NavigationScreenComponent<NavigationParams, {}, Props>却无法识别道具的扩展名。这似乎是由于需要将扩展​​道具类型作为第三个参数发送的:

  export type NavigationScreenComponent<
    Params = NavigationParams,
    Options = {},
    Props = {}
  > = React.ComponentType<NavigationScreenProps<Params, Options> & Props> & {
    navigationOptions?: NavigationScreenConfig<Options>;
  };
  

来自react-navigation.d.ts

答案 6 :(得分:0)

这似乎可行:

public static navigationOptions: NavigationScreenOptionsGetter<
  NavigationScreenOptions
> = (navigation, stateProps) => ({
  title: navigation.state.params.someValue,
});

答案 7 :(得分:0)

在Props的界面中,您无需直接描述所有navigation functions(例如,导航),而是可以直接扩展NavigationScreenProp

就我而言,必须强制eslint避免产生错误。

import { StackNavigator, NavigationScreenProp } from 'react-navigation';

export interface HomeScreenProps extends NavigationScreenProp {
/* your custom props here */
};

export class HomeScreen extends React.Component<HomeScreenProps, object> {

  render() {
    return (
      <View style={styles.container}>       
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </View>
    );
  }
}

答案 8 :(得分:0)

如果您的does not worktsconfig.json,则"strictNullChecks": true部分包含错误。在这种情况下,确实存在错误,因为在

行中

navigation.state.params.someValue

params是可选的。您可以做的是检查该值是否在内部传递,否则提供默认值,例如:

title: navigation.state.params && navigation.state.params.someValue || 'Default title'

答案 9 :(得分:0)

我认为使用react-navigation 5.X现在更简单了。以下是输入传递到屏幕/组件的提示navigation道具的方法:

export default class Header extends React.Component<{
    navigation: StackNavigationHelpers;
}> {
...
}

Ps:经过这些版本的测试

"@react-navigation/native": "^5.2.3",
"@react-navigation/stack": "^5.3.1",

答案 10 :(得分:0)

如果您正在传递由

定义的 nest 道具
// adding an single entry for Australia
// i.e. France = 3, China = 2, Australia = 1
const csv = `Year,City,Sport,Discipline,Athlete,Country,Gender,Event,Medal
2012,London,Gymnastics,Trampoline,"HUANG, Shanshan",CHN,Women,Individual,Silver
2012,London,Gymnastics,Trampoline,"HE, Wenna",CHN,Women,Individual,Bronze
2012,London,Handball,Handball,"ABALO, Luc",FRA,Men,Handball,Gold
2012,London,Handball,Handball,"ACCAMBRAY, William",FRA,Men,Handball,Gold
2012,London,Handball,Handball,"BARACHET, Xavier",FRA,Men,Handball,Gold
2012,London,Swimming,Swimming,"FAST, Freddie",AUS,Men,Swimming,Gold`;

// parse csv
const data = d3.csvParse(csv);

// use Year as filter and set N for top countries
const yearFilter = "2012";
const n = 2;

// filter data
const filtered = data.filter(d => d.Year === yearFilter);

// group, roll-up, sort, slice and map !
const topN = d3.rollups(
  filtered,
  v => v.length,
  d => d.Country
)
.sort((a, b) => d3.descending(a[1], b[1]))  
.slice(0, n) 
.map(d => d[0]);
 
console.log(topN);

对于一个组件,最好的输入方式是:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.0.0/d3.min.js"></script>