简体   繁体   English

“对象作为 React 子对象无效”和短绒

[英]"Objects are not valid as a React child" and linters

I have an issue about a simple component and I don't know why.我有一个关于简单组件的问题,我不知道为什么。 Here is my error and my code :这是我的错误和我的代码:

Error: Objects are not valid as a React child (found: object with keys {Cfor, children}).错误:对象作为 React 子对象无效(找到:带有键 {Cfor, children} 的对象)。 If you meant to render a collection of children, use an array instead.如果您打算渲染一组子项,请改用数组。

import React from 'react';
import './Label.css';

export default function Label(Childn, Cfor) {
  return (
    <label className="label mr-10" htmlFor={Cfor}>
      {Childn}
    </label>
  );
}

I used some linters and I'm trying to follow the style guide of airbnb.我使用了一些短绒,我正在尝试遵循 airbnb 的风格指南。 But in another branch of my project which hasn't the linters, this code works.但是在我项目的另一个没有 linter 的分支中,这段代码有效。 So I guess it's a problem of compatibility with the linters.所以我想这是与 linter 的兼容性问题。 Here is my devDependencies and my .eslintrc.json这是我的 devDependencies 和我的 .eslintrc.json

  "devDependencies": {
    "eslint": "^7.13.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jest": "^24.1.0",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-react": "^7.21.5",
    "eslint-plugin-react-hooks": "^4.2.0",
    "stylelint": "^13.7.2",
    "stylelint-config-standard": "^20.0.0"
  }
{
    "env": {
        "browser": true,
        "es2021": true,
        "jest": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "airbnb",
        "airbnb/hooks"
    ],
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
    }
}

How can I fix that?我该如何解决? Some has an idea?有人有想法吗?

Thanks by advance!提前致谢!

Functional components' first parameter should be props which is an object.功能组件的第一个参数应该是props ,它是一个对象。 then you access children or other props from it然后你可以从中访问孩子或其他道具

export default function Label(props) {
  const { children, Cfor } = props;
  return (
    <label className="label mr-10" htmlFor={Cfor}>
      {children}
    </label>
  );
}

In addition, you cannot render an object directly.此外,您不能直接渲染对象。 Instead you can render JSON.stringify(object)相反,您可以呈现JSON.stringify(object)

import React from 'react';
import './Label.css';

export default function Label({Childn, Cfor}) { // <--- attention
  return (
    <label className="label mr-10" htmlFor={Cfor}>
      {Childn}
    </label>
  );
}

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

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