4

提交表单时,如果服务器发回错误的响应,我希望显示一个 2.5 秒的小弹出窗口。

逻辑相当简单,但是,我无法弄清楚如何让这个弹出窗口在状态管理(在我的例子中是 MobX)的某个地方监听布尔值。我可以很好地将内容放入弹出窗口,但是,触发器是一个按钮(如果单击它,内容将显示) - 但是我如何让它在某处监听布尔值?

这里相当简单的类:

import React from "react";
import { Popup, Button } from "semantic-ui-react";
import { inject } from "mobx-react";
const timeoutLength = 2500;

@inject("store")
export default class ErrorPopup extends React.Component {

    state = {
        isOpen: false
    };

    handleOpen = () => {
        this.setState({
            isOpen: true
        });

        this.timeout = setTimeout(() => {
            this.setState({
                isOpen: false
            })
        }, timeoutLength)
    };

    handleClose = () => {
        this.setState({
            isOpen: false
        });
        clearTimeout(this.timeout)
    };

    render () {

        const errorContent = this.props.data;


        if(errorContent){
            return(
                <Popup
                    trigger={<Button content='Open controlled popup' />}
                    content={errorContent}
                    on='click'
                    open={this.state.isOpen}
                    onClose={this.handleClose}
                    onOpen={this.handleOpen}
                    position='top center'
                />
            )
        }
    }
}

但是,触发值是一个按钮,如果this.props.data存在则呈现。但这不是我希望的行为;我只是想让弹出窗口在this.props.data存在时呈现(并因此触发);true或者,如果需要,我可以提供带有道具的值。

但是如何在不作为悬停/按钮的情况下触发该组件?

4

1 回答 1

3

传入 isOpen 道具怎么样?然后你可以在 componentWillReceiveProps 钩子上添加一些逻辑:

import React from "react";
import { Popup, Button } from "semantic-ui-react";
import { inject } from "mobx-react";
const timeoutLength = 2500;

@inject("store")
export default class ErrorPopup extends React.Component {

 constructor(props) {
   super(props);
   this.state = {
     isOpen: false,
   }
 };

  //This is where you trigger your methods
  componentWillReceiveProps(nextProps){
    if(true === nextProps.isOpen){
      this.handleOpen();
    } else {
      this.handleClose();
    }
  }

  handleOpen = () => {

    this.setState({
      isOpen: true
    });

    this.timeout = setTimeout(() => {
      //No need to repeat yourself - use the existing method here
      this.handleClose();
    }, timeoutLength)
  };

  handleClose = () => {
    this.setState({
      isOpen: false
    });
    clearTimeout(this.timeout)
  };

  render () {

    const errorContent = this.props.data;

    if(errorContent){
      return(
        <Popup
          trigger={<Button content='Open controlled popup' />}
          content={errorContent}
          on='click'
          open={this.state.isOpen}
          position='top center'
        />
      )
    }
  }
}

无需处理延迟 - 您可以简单地传入 isOpen 道具,这样就可以了。

在这里,它在您的父组件的渲染中可能看起来像:

let isOpen = this.state.isOpen; 
<ErrorPopup isOpen={isOpen}/>

设置此值以控制弹出窗口,理想情况下,这应该是父组件状态的一部分。将有状态组件作为父组件对于重新渲染弹出窗口很重要

于 2017-06-08T13:14:53.290 回答