问题
Can someone please help explain this error? I have tried a few different ways to write the React.Component. Is there something missing?
Error:
4:7 warning 'ScrollingHorizontally' is defined but never used no-unused-vars
Component:
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>
)
}
}
I have also tried:
import React from 'react'
import HorizontalScroll from 'react-scroll-horizontal'
class ScrollingHorizontally extends React.Component {
...
回答1:
To answer your question, the original warning you were receiving is that you defined the variable ScrollingHorizontally
but never used it. Even though it is a class it is still a defined variable. It would be easier to demonstrate this error with standard variables:
const things = 123;
const stuff = 456; // this will throw an warning because it is never used.
console.log(things);
The same things happens with classes. If you define a class within a file and never use it, you will receive that warning. Exporting a class from a file will effectively be using it because you are performing the action of exporting it.
--
Why does this error occur?
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
This is pretty straight forward, you didn't export the class from your file so when you imported the component into your index.js
file it didn't find anything. Not all classes within a file automatically get exported, you need to explicitly declare that they should be exported. This allows you to keep certain classes or variables private
to a specific file.
MDN - Export (this link breaks down the different types of exporting)
Example with multiple components in one file:
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';
// ...
来源:https://stackoverflow.com/questions/55143358/warning-scrollinghorizontally-is-defined-but-never-used-no-unused-vars