警告“ScrollingHorizo​​ntally”已定义但从未使用 no-unused-vars

2023-12-07

有人可以帮忙解释这个错误吗?我尝试了几种不同的方法来编写 React.Component。是不是少了点什么?

Error:

4:7 警告“ScrollingHorizo​​ntally”已定义但从未使用 no-unused-vars

成分:

import React, { Component } from 'react'
import HorizontalScroll from 'react-scroll-horizontal'

class ScrollingHorizontally extends Component {
  render() {
    const child   = { width: `30em`, height: `100%`}
    const parent  = { width: `60em`, height: `100%`}
    return (
      <div style={parent}>
        <HorizontalScroll>
            <div style={child} />
            <div style={child} />
            <div style={child} />
        </HorizontalScroll>
      </div>
    )
  }
}

我也尝试过:

import React from 'react'
import HorizontalScroll from 'react-scroll-horizontal'

class ScrollingHorizontally extends React.Component {
  ...

为了回答您的问题,您收到的原始警告是您定义了变量ScrollingHorizontally但从未使用过它。即使它是一个类,它仍然是一个已定义的变量。使用标准变量来演示此错误会更容易:

const things = 123;
const stuff = 456; // this will throw an warning because it is never used.

console.log(things);

同样的事情也会发生在课堂上。如果您在文件中定义了一个类并且从不使用它,您将收到该警告。从文件导出类将有效地使用它,因为您正在执行导出它的操作。

--

为什么会出现这个错误?

元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:未定义。您可能忘记从定义它的文件中导出组件,或者您可能混淆了默认导入和命名导入。

这非常简单,您没有从文件中导出该类,因此当您将组件导入到您的文件中时index.js文件没有找到任何东西。并非文件中的所有类都会自动导出,您需要显式声明应导出它们。这允许您保留某些类或变量private到特定文件。

MDN - 导出(此链接详细介绍了不同类型的导出)

一个文件中包含多个组件的示例:

父级.js

import React from 'react';


// This component is not exported, can only be used within
// this file.
class Child extends React.Component {
    // ...
}

// This component is not used in the file but is exported to be
// used in other files. (named export)
export class RandomComponent extends React.Component {
    // ...
}

// This component is exported as the default export for the 
// file. (default export)
export default class Parent extends React.Component {

    //...

    render() {
        return <Child />
    }
}

index.js

import React from 'react';

import Parent, { RandomComponent } from './parent.js';

// ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

警告“ScrollingHorizo​​ntally”已定义但从未使用 no-unused-vars 的相关文章

随机推荐