[英]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.