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

问题描述 投票:-1回答:2

朋友们!我弄清楚为什么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')
);
javascript reactjs react-proptypes
2个回答
2
投票

使用prop类型,您可以检查传递给组件的道具。 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')
);

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.