反应。 PropTypes.objectOf(PropTypes.number) - 它是如何工作的?

时间:2018-03-02 12:58:40

标签: javascript reactjs react-proptypes

朋友们!我弄清楚为什么PropTypes.objectOf(PropTypes.number)不适用于道具ar?我想在发布之前进行类型检查,但它不起作用。

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')
);

2 个答案:

答案 0 :(得分:2)

使用道具类型,您可以检查传递给组件的道具。 ar不是道具,而是你在其中定义的对象。

选中此PropTypes

你应该检查一个道具名称:

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

选中此项以清除道具Components and Props

如果您的目标是检查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')
);

答案 1 :(得分:0)

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')
);

好吧,我在解决道具的陪同错误时遇到了同样的问题。它不会简单地接受一个对象作为我的道具类型,所以我必须定义我在那里期望的实际形状。

此外,在此示例中,您应将ar作为道具传递给组件并定义其形状。