【发布时间】:2019-10-17 13:58:24
【问题描述】:
我正在使用 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;
我在这里做错了什么?
【问题讨论】:
-
您的代码中似乎有多个版本的 react
标签: reactjs typescript react-hooks