有人可以帮忙解释一下这个错误吗?我尝试了几种不同的方法来编写React.Component。有什么遗失的吗?
错误:
4:7警告'ScrollingHorizontally'已定义,但从未使用过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);
课程也是如此。如果您在文件中定义一个类并且从不使用它,您将收到该警告。从文件导出类将有效地使用它,因为您正在执行导出它的操作。
--
为什么会出现此错误?
元素类型无效:期望一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:undefined。您可能忘记从其定义的文件中导出组件,或者您可能混淆了默认导入和命名导入。
这很简单,你没有从你的文件中导出类,所以当你将组件导入你的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';
// ...