如何解决对象解构 eslint 抛出 react/prop-types
export const Top = (props) => {
return (
<div key={props.id} className={props.borderColor}>
<div className="h-3/4 bg-green-200 border-black border-1 grid justify-items-center">
<p className="text-xl font-bold">{props.title}</p>
...
在我阅读 Airbnb JavaScript 样式指南之前,我的代码看起来如此。
然后我将其更改为以下内容。
export const Top = (props) => {
const { id,borderColor,title,price,color } = props;
return (
<div key={id} className={borderColor}>
<div className="h-3/4 bg-green-200 border-black border-1 grid justify-items-center">
<p className="text-xl font-bold">{title}</p>
我喜欢它,但 eslint 指责我犯了以下错误:
'id' is missing in props validation react/prop-types
经过简短的研究,我发现了以下内容 React eslint error missing in props validation
所以我改变了我的代码。
export const Top = () => {
const { id,color } = this.props;
return (
<div key={id} className={borderColor}>
<div className="h-3/4 bg-green-200 border-black border-1 grid justify-items-center">
<p className="text-xl font-bold">{title}</p>
Stateless functional components should not use `this` react/no-this-in-sfc
Airbnb 指南指出以下是最好的方法。
function getFullName({ firstName,lastName }) {
return `${firstName} ${lastName}`;
}
但是如果括号中的参数超过 2 个怎么办?我记得这在 robert c martin 的干净代码书中被认为是糟糕的。
什么对你有用?我也不想禁用任何规则,但想以一种干净的方式解决问题。
解决方法
export const Top = (props) => {
const { id,borderColor,title,price,color } = props;
return (
<div key={id} className={borderColor}>
<div className="h-3/4 bg-green-200 border-black border-1 grid justify-items-center">
<p className="text-xl font-bold">{title}</p>
这是对的。只是你必须做一些额外的代码。
-
在导出块之前,您必须导入
PropTypes
import React from 'react'; import PropTypes from 'prop-types';
-
然后在导出块之后你必须添加这些
Top.propTypes = { id: PropTypes.oneOfType(PropTypes.number,PropTypes.string),borderColor: PropTypes.string,title: PropTypes.string,price: PropTypes.number,color: PropTypes.string,}
有关详细信息,请查看此链接 https://reactjs.org/docs/typechecking-with-proptypes.html
,你得到了第二个错误(this
),因为函数组件中没有 this
试试:
export const Top = (props) => {
const { id,color } = props;
...
您可以使用此方法获取组件的 props
1)
export default MyComponent(props){
...
}
- 解构道具对象
export default MyComponent({prop1,prop2,prop3} ...){
...
}
我不喜欢第二个选项,因为如果明天你要添加 10 个新道具,你需要确保将它添加到括号中,之后括号看起来会比之前长得多,这使得它不可读>
但如果它是一个小组件,第二个选择是最好的
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。