簡體   English   中英

Object 解構 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

經過簡短的研究后,我在道具驗證中遇到了以下 React eslint 錯誤

所以我改變了我的代碼。

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

可能不是一個好的解決方案,我不使用類。

Airbnb 指南說以下是 go 的最佳方式。

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 ),因為 function 組件中沒有this

嘗試:

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

您可以使用此方法獲取組件的道具
1)

export default MyComponent(props){
...
}
  1. 解構道具 object
export default MyComponent({prop1, prop2, prop3} ...){
...
}

我不喜歡第二個選項,因為如果明天你將添加 10 個新道具,你需要確保將其添加到括號中,之后括號看起來會比之前長得多,這使得它不可讀

但如果它是一個小組件,第二個選項是最好的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM