首页 > 解决方案 > 从本地库导入时,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;

我在这里做错了什么?

标签: reactjstypescriptreact-hooks

解决方案


由于这似乎是一个导入/导出问题,请尝试将您的导出更改为:

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 };

推荐阅读