React是什么类型?

时间:2018-10-12 14:18:50

标签: javascript reactjs atlaskit

好吧,我看到下面的代码片段,我想知道type Props到底是什么?与流量有关吗?还是和道具类型有关?

如何在定义为类的组件中使用它?

我在以下的React-Router示例中看到了它:https://atlaskit.atlassian.com/packages/core/navigation

代码段:

// @flow
import React from "react";
import { AtlassianIcon } from "@atlaskit/logo";
import Lorem from "react-lorem-component";
import Page from "@atlaskit/page";
import Navigation, { AkContainerTitle } from "@atlaskit/navigation";
import RouterLinkComponent from "./RouterLinkComponent";
import RouterLinkItem from "./RouterLinkItem";

// @flow

type Props = {
  title: string,
  currentPath: string
};

const PageNavigation = ({ title, currentPath }: Props) => (
  <Page
    navigation={
      <Navigation
        containerHeaderComponent={() => (
          <AkContainerTitle
            href="/iframe.html"
            icon={<AtlassianIcon label="atlassian" />}
            linkComponent={RouterLinkComponent}
            text="Dashboard"
          />
        )}
        globalPrimaryIcon={<AtlassianIcon label="Home" size="small" />}
        globalPrimaryItemHref="/iframe.html"
        linkComponent={RouterLinkComponent}
      >
        <RouterLinkItem
          text="Page 1"
          to="/page1"
          isSelected={currentPath === "/page1"}
        />
        <RouterLinkItem
          text="Page 2"
          to="/page2"
          isSelected={currentPath === "/page2"}
        />
        <RouterLinkItem
          text="Page 3"
          to="/page3"
          isSelected={currentPath === "/page3"}
        />
        <RouterLinkItem
          text="Page 4"
          to="/page4"
          isSelected={currentPath === "/page4"}
        />
      </Navigation>
    }
  >
    <div>
      <h1>{title}</h1>
      <Lorem count="30" />
    </div>
  </Page>
);

export default PageNavigation;

2 个答案:

答案 0 :(得分:5)

它是流类型检查器的一部分。查看文档:{​​{3}}

如果是PropTypes,则看起来像这样:

PageNavigation.propTypes = {
  title: string,
  currentPath: string
};

答案 1 :(得分:0)

以下是有用的道具类型列表

ComponentName.propTypes = {
  someVariablePropNameA: PropTypes.string.isRequired,
  someVariablePropNameB: PropTypes.object.isRequired,
  someVariablePropNameC: PropTypes.arrayOf(PropTypes.object).isRequired,
  someVariablePropNameD: PropTypes.number,
  someVariablePropNameE: PropTypes.bool
};

这些是预期的props数据类型,它们通常在组件内部,通常传递到组件中。失败的道具类型不应破坏组件,但会显示错误,警告您它们失败了。通常,我们会在控制台日志中查看它。

此外,您可以使用默认的道具类型

MatchRating.defaultProps = {
  someVariablePropNameA: "",
  someVariablePropNameB: {},
  someVariablePropNameC: [{}],
  someVariablePropNameD: 0,
  someVariablePropNameE: false
};

您需要像这样

将此包包含在标题中
import PropTypes from "prop-types";

这只是测试错误的一种方法。应该始终使用。

现在是完整示例


import React, { PureComponent } from "react";
import PropTypes from "prop-types";

class ComponentName extends PureComponent {
}

ComponentName.propTypes = {

};

ComponentName.defaultProps = {

};

export default ComponentName;

希望这会有所帮助