![](/img/trans.png)
[英]how to throw a react-alert inside of a function in a class based component
[英]How can I display messages in component with react-alert?
我正在使用 reactjs。 我想在带有 react-alert 组件的组件中显示警报。 https://www.npmjs.com/package/react-alert我按照给出的包装 index.js 文件。
但是当我尝试在表单中使用alert.show ("sdfsdfsdfsf")
时,出现以下错误。
在表单中显示消息?
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App/App';
import { transitions, positions, Provider as AlertProvider } from 'react-alert'
import AlertTemplate from 'react-alert-template-basic'
import { Provider } from 'react-redux';
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
};
ReactDOM.render(
<Provider store={store}>
<AlertProvider template={AlertTemplate} {...options}>
<App/>
</AlertProvider>
</Provider>,
document.getElementById('root'));
myForm.js
import { useAlert } from "react-alert";
const alert = useAlert();
class myForm extends Component {
constructor(props) {
super(props);
.........
render() {
return(
<div> alert.show("Alert test") </div>
)
}
您正在使用:
return(
<div> alert.show("Alert test") </div>)
}
但是您需要使用事件来显示该警报。
改用这个:
return(<div onClick={() =>
{alert.show('Alert test')}}></div>)
}
您不能在 render 方法中调用 function / 方法,除非它用花括号括起来。 jsx 中需要大括号,以让解析器知道您要运行一些 javascript 代码。
尝试以下操作:
render() {
return (
<div>{alert.show("Alert test")}</div>
);
}
The react-alert package on npm also has a nice example when using an onClick handler https://www.npmjs.com/package/react-alert
const App = () => {
const alert = useAlert()
return (
<button
onClick={() => {
alert.show('Oh look, an alert!')
}}
>
Show Alert
</button>
)
}
export default App
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.