friends! I figure out why PropTypes.objectOf(PropTypes.number)
does not apply to 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.
Check this 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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.