最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set required props on component - Stack Overflow

programmeradmin2浏览0评论

Say that I create a custom component like this:

const MyComponent = (props) => (
  <div
    className={props.name}
    id={props.id}>
    {props.children}
  </div>
)

And I need to make sure that props contain the variables name and id, because otherwise what I want to do is not going to work (now I know that this code will work anyhow, but hypothetically say that it won't).

Is there a way in React to demand that certain props are passed to a component?

Maybe this is something that is obvious, but I couldn't find any information about it.

Say that I create a custom component like this:

const MyComponent = (props) => (
  <div
    className={props.name}
    id={props.id}>
    {props.children}
  </div>
)

And I need to make sure that props contain the variables name and id, because otherwise what I want to do is not going to work (now I know that this code will work anyhow, but hypothetically say that it won't).

Is there a way in React to demand that certain props are passed to a component?

Maybe this is something that is obvious, but I couldn't find any information about it.

Share Improve this question asked Jul 24, 2017 at 19:23 martin36martin36 2,3634 gold badges22 silver badges31 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

You can use PropTypes. It was earlier a part of React but now it has its own npm package, https://www.npmjs.com/package/prop-types. This will give you a runtime error if ther props are not provided. Its also useful, because linters can warn you if you miss them.
https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md

import React from 'react';
import PropTypes from 'prop-types'; 

const MyComponent = (props) => (
  <div
    className={props.name}
    id={props.id}>
    {props.children}
  />
);

MyComponent.propTypes = {
  name: PropTypes.string.isRequired,
  id: PropTypes.string.isRequired,
  element: PropTypes.arrayOf(PropTypes.element).isRequired
};
发布评论

评论列表(0)

  1. 暂无评论