javascript - 对所有消息使用单个 React-Toastr 容器

标签 javascript reactjs ecmascript-6 react-router

我正在使用 ReactJS 和 React-Router 构建 SPA。应用程序是我的主要组件,其他一切都源于此。在该组件上,我添加了一个 ToastContainer,它在该组件中运行良好。我已将该功能传递给子组件,希望它们可以调用并显示消息。当我尝试这样做时,我得到了

Uncaught TypeError: Cannot read property 'toastContainer' of undefined

应用/主要组件

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, IndexRoute, browserHistory, hashHistory } from 'react-router';
import ParameterContainer from './components/parameter/parameter-container';
import ParameterValueContainer from './components/parameter/parameter-value-container';
import NavMenu from './components/navigation/nav-menu';
import {Alert} from 'react-bootstrap';
import ReactToastr from 'react-toastr';
import {ToastContainer, ToastMessage} from 'react-toastr';

let ToastMessageFactory = React.createFactory(ToastMessage.animation);

// Main component and root component
export default class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            userId: null,
            roles: null,
            parameterTypes: {
                'STRING': 'STRING',
                'BOOLEAN': 'BOOLEAN',
                'INTEGER': 'INTEGER',
                'DECIMAL': 'DECIMAL'
            },
            parameterGroups: {
                1: 'POS',
                2: 'MenuStructure'
            }
        };
    }

    componentDidMount() {
        //this.addAlert('Success', 'Parameter Created');
        this.addErrorAlert('Ohhhh snap!', 'You messed up Rodney, you messed up bad!');
    }

    addAlert(title, message) {
        this.refs.toastContainer.success(
            title,
            message,
            {
                timeOut: 10000,
                extendedTimeOut: 10000,
                preventDuplicates: true,
                positionClass: "toast-bottom-full-width",
                showMethod: "fadeIn",
                hideMethod: "fadeOut"
            }
        );
    }

    addErrorAlert(title, message) {
        this.refs.toastContainer.error(
            message,
            title,
            {
                timeOut: 10000,
                extendedTimeOut: 10000,
                preventDuplicates: true,
                positionClass: "toast-bottom-full-width",
                showMethod: "fadeIn",
                hideMethod: "fadeOut"
            }
        );
    }

    render() {

        return (
            <div>
                <NavMenu />
                <div className="container-fluid">
                    {React.Children.map(
                        this.props.children,
                        child => React.cloneElement(child,
                            {
                                parentState: this.state,
                                path: this.props.route.path,
                                alertCallback: this.addErrorAlert
                            })
                    )}
                    <ToastContainer ref="toastContainer" toastMessageFactory={ToastMessageFactory} className="toast-bottom-full-width">
                    </ToastContainer>
                </div>
            </div>
        )
    }
}

// page for 404
class NoMatch extends React.Component {
    render() {
        return (
            <div className="container">
                <Alert bsStyle="danger">
                    <h1>404: Not Found</h1>
                    <h3>The requested resource does not exist!</h3>
                </Alert>
                <img src="images/404.png" style={{display: 'block', margin: '0 auto', width: 300, height: '*'}} />
            </div>
        )
    }
}

// render the application
ReactDOM.render((
    <Router history={hashHistory}>
        <Route path="/" component={App}>
            <Route path="parameter" component={ParameterContainer} />
            <Route path="parametervalues" component={ParameterValueContainer} />
            <Route path="*" component={NoMatch}/>
        </Route>
    </Router>
), document.getElementById('react'))

我在子组件中使用这样的回调

componentDidMount() {
    this.props.alertCallback("OHHHH NOOOO!!!!", "Something has gone wrong!");
    this.fetchFromApi();
}

最佳答案

在你提到它在 App/Container 中工作之后,我建议你在你的构造函数中绑定(bind)你的函数,所以它看起来像这样:

constructor(props) {
    super(props);
    this.state = {
        userId: null,
        roles: null,
        parameterTypes: {
            'STRING': 'STRING',
            'BOOLEAN': 'BOOLEAN',
            'INTEGER': 'INTEGER',
            'DECIMAL': 'DECIMAL'
        },
        parameterGroups: {
            1: 'POS',
            2: 'MenuStructure'
        }
    };
    this.addErrorAlert = this.addErrorAlert.bind(this);
}

这应该可以解决您的问题,让我知道它是否有效。

如果您想了解有关事件处理的更多信息,可以阅读此 documentation .在那里你会找到为什么你需要绑定(bind)每个事件处理程序的解释。

关于javascript - 对所有消息使用单个 React-Toastr 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42421223/

相关文章:

javascript - 有没有办法在不使用 Next 或 Gatsby 的情况下使 ReactJs SEO 友好?

javascript - 如何提取没有标题的响应内容(仅正文)?使用 Jquery

javascript - React JS 对象集合的状态更新

javascript - 在 React JS 中更新数组会覆盖旧值

Reactjs 是否有多种元素类型声明的快捷方式

javascript - 在保持订阅的同时更改可观察流

javascript - 在 Chart.js 中更改工具提示颜色

javascript - 如何使用 ES6 语法导入 pg-promise?

javascript - 为什么在 react 中更新状态时状态会以这种方式表现

javascript - EXPRESS:Router.use() 需要一个中间件函数,但得到一个对象