reactjs - 从本地库导入时,React 钩子不起作用
问题描述
我正在使用 React 导入一个带有 useState 钩子的函数,这似乎破坏了它。我有一个带有钩子的反应版本:
npm ls react => react@16.10.2
npm ls react-dom => react-dom@16.10.2
我可以很好地使用组件。当我包含一个钩子时,我会看到“无效的钩子调用”屏幕。
在我的图书馆项目中,我有:
/**
* @class ExampleComponent
*/
import * as React from 'react'
import styles from './styles.css'
export default function ThingyDefault() {
return <p>hi</p>
}
export type Props = { text: string }
export class ExampleComponent extends React.Component<Props> {
render() {
const {
text
} = this.props
return (
<div className={styles.test}>
Example Component: {text}
</div>
)
}
}
////////////////// THIS DOESN'T SEEM TO WORK //////////////////
export function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = React.useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
在我使用该库的项目中:
import React from 'react';
import './App.css';
import ThingyDefault, {ExampleComponent, Example} from 'thingy';
const App: React.FC = () => {
return (
<div>
<ThingyDefault />
<ExampleComponent text='hello' />
{/* commenting this component out makes it work */}
<Example />
</div>
);
}
export default App;
我在这里做错了什么?
解决方案
由于这似乎是一个导入/导出问题,请尝试将您的导出更改为:
const Example = () => {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = React.useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export { Example };
推荐阅读
- python - Pyspark - 用 pysaprk 中的第一个单词替换 2 个或更多连续单词
- javascript - 所有正文内容在导航上下移动(HTML & CSS)
- batch-file - 将 curl 命令输出存储在批处理脚本的变量中
- html - Asp.NET MVC 表单条目显示为外部站点的链接?
- javascript - 通过 d3.js 显示从 div html 获取的变量值
- typescript - “ITestData”可分配给“IEntityData”类型的约束,但“IEntityData”可以用不同的约束子类型实例化
- c# - 如何对以下场景进行单元测试?
- python - 如何防止通过单击 PYQT 中的滑块来更改滑块的值?
- python - R:无法在 Windows 下使用带有 SYSTEM 帐户的包网状体
- c - 如何在 C 中隐藏内部依赖关系?