【问题标题】:warning 'ScrollingHorizontally' is defined but never used no-unused-vars警告 'ScrollingHorizo​​ntally' 已定义但从未使用 no-unused-vars
【发布时间】:2019-03-13 13:43:58
【问题描述】:

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

错误:

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 {
  ...

【问题讨论】:

  • 第一个 sn-p 中没有 Scroll 变量。也许是因为您没有从模块中导出组件?
  • 我刚刚在第二个sn-p中重命名了,和ScrollingHorizo​​ntally差不多吧?
  • 是的,但是您警告您创建此问题是为了说Scroll。我假设它在第一个 sn-p 中对 ScrollingHorizontally 说了同样的话。您是否从模块中导出了ScrollingHorizontally
  • 对不起,这是误导,我会改变它,错误是一样的 - 警告'ScrollingHorizo​​ntally'已定义但从未使用过
  • 这不是错误 - 它只是警告您,您已经定义了一个组件,但从未在任何地方使用它。一旦您导出组件并开始使用它,它就会消失。

标签: reactjs gatsby


【解决方案1】:

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

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

console.log(things);

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

--

为什么会出现这个错误?

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

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

MDN - Export (this link breaks down the different types of exporting)

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

parent.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';

// ...

【讨论】:

    猜你喜欢
    • 2020-04-21
    • 2022-06-20
    • 2017-11-20
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 2020-07-04
    相关资源
    最近更新 更多