首页 > 解决方案 > 接收错误:功能组件中的挂钩调用无效

问题描述

我正在尝试创建一个简单的组件并将其发布到 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 应用程序(但不是独立组件),我从来没有遇到过这个问题。任何建议将不胜感激。

标签: javascriptreactjsreact-hooks

解决方案


推荐阅读