我使用https://www.npmjs.com/package/create-react-library创建了一个React库。 并已成功地在其他React项目中使用它。 但当我尝试在库中使用React Hooks功能时,会出现以下错误。
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
.....
我的图书馆 我刚尝试在我的组件中使用useState,代码如下。
import React, { useState } from 'react'
const General = (props) => {
const [count, setCount] = useState(0);
return (
<div>
General component
</div>
)
}
export default General
我正在使用"react": "^16.8.6"
和"react-dom": "^16.8.6"
我的React应用是使用https://github.com/facebook/create-react-app创建的,并按以下方式使用上述库。
import Reactfrom 'react'
import { General } from 'my.lib'
const accountSummary = props => {
return (
<div>
<General>
</div>
)
}
export default accountSummary
两者使用了相同的React版本,并且库也使用了与peerDependencies
中相同的React DOM和React版本。
"my.library": "file:../my.library"
在 py package.json 中引用它。Lib 在另一个 React 实例中单独运行。如果我将其作为 npm 库发布并使用它,则可以正常工作。 - Janith Widarshana