javascript - 接收错误:功能组件中的挂钩调用无效
问题描述
我正在尝试创建一个简单的组件并将其发布到 npm。在发布之前,我想测试一下组件;但是,每当我在测试应用程序中使用我的组件时,我都会得到以下信息:Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
这是有问题的组件:
我的组件.tsx:
import React, { useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return (
<div>
<pre></pre>
<button onClick={increment} name='test1'>
Increment
</button>
<button onClick={decrement} name='test2'>
Decrement
</button>
</div>
);
};
export default MyComponent;
索引.ts:
import MyComponent from './MyComponent';
import './index.css';
export { MyComponent };
这是测试应用程序:
import React from 'react';
import './App.css';
import { MyComponent } from 'one-select';
function App() {
return (
<div className="App">
<div>
<MyComponent />
</div>
</div>
);
}
export default App;
MyComponent
通过导入到测试应用程序中npm install /path/to/mycomponent-project
我之前创建过其他 React 应用程序(但不是独立组件),我从来没有遇到过这个问题。任何建议将不胜感激。
解决方案
推荐阅读
- node.js - 如何使用 .on 同时调用 console.log 和 console.log()?
- google-apps-script - 包括脚本的附加条件
- php - 如何通过php函数导出mysql数据库中某些表中的某些行?
- google-earth-engine - 如何在谷歌地球引擎中计算时间序列图像的区域统计?
- hyperlink - 如何在使用 LinkTransformator 时管理内部页面的锚点(带有主题标签的链接)?
- c# - 如何有效地将属性作为列表从 IReadOnlyCollection 获取?
- python-3.x - Python3.7 子进程输出到终端但没有收到 SIGINT
- sql - SQL Server - 将 column_id 设置为外键
- reinforcement-learning - 困难的强化学习查询
- python - 多重继承未按预期工作