繁体   English   中英

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

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

朋友们! 我知道为什么PropTypes.objectOf(PropTypes.number)不适用于prop 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')
);

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

检查此PropTypes

您应该检查名称是一个道具:

Greeting.propTypes = {
  name: 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() {
    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')
);

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

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

暂无
暂无

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

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