简体   繁体   English

反应 PropTypes.objectOf(PropTypes.number)-如何工作?

[英]React. PropTypes.objectOf(PropTypes.number) - how it work?

friends! 朋友们! I figure out why PropTypes.objectOf(PropTypes.number) does not apply to prop ar ? 我知道为什么PropTypes.objectOf(PropTypes.number)不适用于prop ar吗? I want to do a type checking before release, but it does not work. 我想在发布前进行类型检查,但是它不起作用。

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import './index.css';

class Greeting extends React.Component {
  render() {

    const ar = {
      a: 123,
      b: '123'
    }

    return (
      <div>Hello, {ar.a}!</div>
    );
  }
}

Greeting.propTypes = {
  ar: PropTypes.objectOf(PropTypes.number)
};

ReactDOM.render(
  <Greeting />,
  document.getElementById('root')
);

With prop types you check the props that pass to your component. 使用道具类型,您可以检查传递给组件的道具。 ar is not a prop but an object you define in it. ar不是道具,而是您在其中定义的对象。

Check this PropTypes 检查此PropTypes

You should check the name which is a prop: 您应该检查名称是一个道具:

Greeting.propTypes = {
  name: PropTypes.number
};

Check this to clear out what props is Components and Props 选中此项以清除什么是道具和道具

Try this if your objective is to check ar: 如果您的目标是检查ar,请尝试以下操作:

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import './index.css';

class Greeting extends React.Component {
  render() {
    return (
      <div>Hello, {this.props.ar.a}!</div>
    );
  }
}

Greeting.propTypes = {
  ar: PropTypes.objectOf(PropTypes.number)
};

const ar = {
  a: 123,
  b: '123'
}

ReactDOM.render(
  <Greeting ar={ar}/>,
  document.getElementById('root')
);
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import './index.css';

class Greeting extends Component {
  render() {

    return (
      <div>Hello, {ar.a}!</div>
    );
  }
}

Greeting.propTypes = {
    ar: PropTypes.objectOf(PropTypes.shape({
        a: PropTypes.number.isRequired,
        b: PropTypes.string.isRequired
    }).isRequired
};

const ar = {
    a: 123,
    b: '123'
}
ReactDOM.render(
  <Greeting ar={ar} />,
  document.getElementById('root')
);

Well, I was facing the same problem while resolving an eslint error for props. 好吧,我在解决道具的陪同错误时遇到了同样的问题。 It won't simply accept an object as my prop type, so I had to define the actual shape I was expecting there. 它不会简单地接受一个对象作为我的道具类型,因此我必须定义在那里期望的实际形状。

Also, in this example, you should pass ar as a prop to component and define its shape. 另外,在此示例中,您应将ar作为道具传递给组件并定义其形状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM