我尝试过使用typescript在私有react
组件库(NPM包)中安装Material-UI
,自定义一些MUI
组件,然后将它们从我自己的包导入到另一个应用程序中。
问题是,它总是在应用程序中抛出一个错误,说:
错误:无效的钩子调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一:
1.你可能有不匹配的React版本和渲染器(比如React DOM)
1.你可能违反了钩的规则
1.您可能在同一个应用程序中有多个React副本,请参阅https://reactjs.org/link/invalid-hook-call了解有关如何调试和修复此问题的提示。
控制台错误:
NPM包内样式化的MUI组件(private-component-library):
import * as React from 'react'
import { makeStyles, Checkbox, CheckboxProps } from '@material-ui/core'
const useStyles = makeStyles((theme) => ({
root: {
'& + .MuiFormControlLabel-label.Mui-disabled': {
color: theme.palette.grey[400],
},
},
}))
export const StyledCheckbox: React.FC<CheckboxProps> = (props) => {
const classes = useStyles()
return (
<Checkbox
className={classes.root}
color='default'
inputProps={{ 'aria-label': 'decorative checkbox' }}
{...props}
/>
)
}
export default StyledCheckbox
我是这样导出包内组件的(index.ts
文件):
export { ThemeProvider } from '@material-ui/core/styles'
export { Box } from '@material-ui/core'
export { StyledCheckbox } from './components/StyledCheckbox'
export theme from 'theme/theme'
导入应用内组件(MyComponent.tsx
文件):
import React, { useState } from 'react'
import { StyledCheckbox } from 'private-component-library'
export const MyComponent: React.FC = () => {
const [error, setError] = useState(false)
const [loading, setLoading] = useState<boolean>(false)
return (
<Box pb={5}>
<StyledCheckbox />
</Box>
);
}
export default MyComponent
App.tsx
的内容
import * as React from 'react'
import { Switch, Route, Redirect, useLocation } from 'react-router-dom'
import { ThemeProvider } from 'private-component-library'
import theme from 'private-component-library'
import MyComponent from './MyComponent'
const App: React.FC = () => {
const location = useLocation()
return (
<ThemeProvider theme={theme}>
<Switch>
<Route path='/' children={<MyComponent />} />
<Redirect
from='/:url*(/+)'
to={{ ...location, pathname: location.pathname.slice(0, -1) }}
/>
</Switch>
</ThemeProvider>
)
}
export default App
和应用程序的index.tsx
文件:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router } from 'react-router-dom'
import App from './App'
ReactDOM.render(
<React.StrictMode>
<Router basename='/home'>
<App />
</Router>
</React.StrictMode>,
document.getElementById('root'),
)
我尝试从我的私有NPM包中删除react
和react-dom
依赖项,甚至将它们添加为peerDependencies
或devDependencies
,但没有帮助。
我也尝试了https://reactjs.org/link/invalid-hook-call的调试步骤,它也无法解决这个问题。
有什么不对吗?
1条答案
按热度按时间sr4lhrrt1#
你必须安装这两个插件“rollup-plugin-peer-deps-external”,“rollup-plugin-terser”,并按照链接。
external: ["react", "react-dom", "@material-ui/core"],
https://blog.logrocket.com/how-to-build-component-library-react-typescript/