对象解构 eslint 抛出 react/prop-types

Object Destructuring eslint throws 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

经过短暂的研究,我发现了以下内容

所以我更改了我的代码。

export const Top = () => {
    const { id, borderColor, title, price, 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

可能不是一个好的解决方案,我不使用 类。

爱彼迎指南指出以下是最佳方式。

function getFullName({ firstName, lastName }) {
  return `${firstName} ${lastName}`;
}

但是如果括号中的参数超过2个怎么办?我记得在 robert c martin 的 clean code book 中,这被认为是糟糕的。

什么适合你?我也不想禁用任何规则,但想以干净的方式解决问题。

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,
    }
    

有关详细信息,请查看此 link https://reactjs.org/docs/typechecking-with-proptypes.html

你得到了第二个错误(this)因为函数组件

中没有this

尝试:

export const Top = (props) => {
    const { id, borderColor, title, price, color } = props;
...

您可以使用此方法获取组件的 props
1)

export default MyComponent(props){
...
}
  1. 解构道具对象
export default MyComponent({prop1, prop2, prop3} ...){
...
}

我不喜欢第二个选项,因为如果明天你要添加 10 个新道具,你需要确保将其添加到括号中,之后括号看起来会比之前长得多,这使得它变得不可读

但如果它是一个小组件,第二个选项是最好的