简体   繁体   English

在“道具”一词的道具验证中反应 eslint 错误

[英]React eslint error missing in props validation on for the word "props"

I have the code below:我有以下代码:

import React from "react";
import "./App.css";
import myPic from "./pics/John_Smith.jpg";

function App() {
  return (
    <div className="App">
            <header className="App-header">
                <div className="App-Modal">
                    <p className="App-Modal-Text">5 Birthdays today</p>
                    {/* <BirthdayCard job="Developer"/> */}
                    <BirthdayCard />
                </div>
      </header>
    </div>
  );
}

const BirthdayCard = (props) => {
    console.log(props);
    return <article className="BArticle">
        <Image></Image>
        <Text></Text>
        <p>{props.job}</p>
    </article>

};

const Image = () => (
    <img src={myPic} alt="" />
 );

const Text = () => {
    return <article className="BText">
        <Name></Name>
        <Age></Age>
    </article>
}

const Name = () => (
    <h5>John Smith</h5>
)

const Age = () => (
    <p>30 years</p>
)

export default App;

I am getting the error;我收到错误消息; "job" is missing in props validation react/prop-types, but this ONLY happens if I use the word "props" as a parameter. props 验证 react/prop-types 中缺少“job”,但只有当我使用“props”这个词作为参数时才会发生这种情况。 If I change it to anything else even "prop", the error goes away.如果我将其更改为其他任何内容,甚至是“道具”,错误就会消失。 Does anyone know why this is and how to fix it to be able to use "props" as a parameter?有谁知道这是为什么以及如何修复它以便能够使用“道具”作为参数?

Prop validations is a way of typechecking the props that a component recieves. Prop 验证是一种对组件接收到的 props 进行类型检查的方法。

For instance, in the case of BirthdayCard you could do something like:例如,在BirthdayCard的情况下,您可以执行以下操作:

import PropTypes from 'prop-types';

BirthdayCard.propTypes = {
  job: PropTypes.string
};

So whenever you use BirthdayCard and pass the prop job with a type other than string you will get a console error warning you that the type should be string.因此,每当您使用BirthdayCard并以字符串以外的类型传递道具作业时,您都会收到控制台错误警告您该类型应该是字符串。

// This throws a console error
<BirthdayCard job={1} />

// This does not throw any error
<BirthdayCard job="programmer" />

If you are not going to be defining prop types you might want to disable this warning.如果您不打算定义道具类型,则可能需要禁用此警告。

As of why it only throws the warning when the name is props.至于为什么它只在名称为道具时抛出警告。

Side note.边注。 You can use object deconstruction to clean your component definitions a little bit.您可以使用 object 解构来稍微清理您的组件定义。

const BirthdayCard = ({ job }) => {
    return <article className="BArticle">
        <Image></Image>
        <Text></Text>
        <p>{job}</p>
    </article>
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM