我的react.js
应用程序中有这段代码:
import { withAlert} from "react-alert";
class Signup extends React.Component {
state={email:'',passwordHash:'',rePasswordHash:''};
onButtonClick = () =>{
if(this.state.passwordHash!==this.state.rePasswordHash){
this.props.alert.error("Wrong password");
}
else{
this.props.alert.show("Creating new account");
}
};
render(){
return(
<ButtonActor name="Sign In" onButtonClick={this.onButtonClick} />
);
}
}
export default withAlert()(Signup);
它在我的SignUp
类中,每当用户尝试创建帐户时,它只需要在两个字段中输入相同或不同的密码。据此,它应该创建一个警报。但是它崩溃了,并给了我这个错误:
Uncaught Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component.
react-alert,我正在使用的库。
有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
如果您使用的是类组件,则:
import { withAlert } from "react-alert";
...
export default withAlert()(Home)
并将其称为:
this.props.alert.show()
答案 1 :(得分:0)
我刚刚用<App/>
包裹了<AlertProvider/>
。
来自doc的示例,现在他们有了更好的doc:
// index.js
import React from 'react'
import { render } from 'react-dom'
import { transitions, positions, Provider as AlertProvider } from 'react-alert'
import AlertTemplate from 'react-alert-template-basic'
import App from './App'
// optional cofiguration
const options = {
// you can also just use 'bottom center'
position: positions.BOTTOM_CENTER,
timeout: 5000,
offset: '30px',
// you can also just use 'scale'
transition: transitions.SCALE
}
const Root = () => (
<AlertProvider template={AlertTemplate} {...options}>
<App />
</AlertProvider>
)
render(<Root />, document.getElementById('root'))
还有一个:
// App.js
import React from 'react'
import { useAlert } from 'react-alert'
const App = () => {
const alert = useAlert()
return (
<button
onClick={() => {
alert.show('Oh look, an alert!')
}}
>
Show Alert
</button>
)
}
它们也具有按钮界面:
import React from 'react'
import { withAlert } from 'react-alert'
const App = ({ alert }) => (
<button
onClick={() => {
alert.show('Oh look, an alert!')
}}
>
Show Alert
</button>
)
export default withAlert()(App)