繁体   English   中英

如何使用 react-alert 在组件中显示消息?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM