React 中的类型是什么?

What is type in React?

嗯,我看到了下面的代码片段,我想知道 type Props 到底是什么?跟流量有关系吗?或者它与道具类型有关?

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

我在此处找到的 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;

它是流类型检查器的一部分。请参阅文档:Type Aliases

如果是 PropTypes 那么它看起来像这样:

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

这是一个有用的列表 prop-types

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

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

此外,您可以像这样使用默认道具类型

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

您需要像这样 header 中包含此包

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;

希望对您有所帮助