反应组件自身状态(UI状态)

时间:2016-07-12 17:09:57

标签: reactjs redux

我正在使用React-toolbox对话框,我希望将其包装为一个简单的确认对话框,它就像alert()一样显示带有消息和关闭按钮的对话框。

所以我有这样的演示组件

const ConfirmationDialog =({active, size, title,  message}) => {

  const onClickConfirm = ()=> {
    active = false;
  }

  return (
      <Dialog
        active={active}
        title={title}
        type={size}
      >
        <p>{message}</p>
          <button onClick={onClickConfirm}>Close</button>
      </Dialog>
  );
}

export default ConfirmationDialog;

active来自道具,因此我需要时会显示确认对话框,但我希望关闭按钮只关闭对话框。

我真的必须通过handleOnClose功能吗?每次我想使用这个组件时,都必须传递该函数。 或者我真的必须创建一个容器类来实现这样一个简单的操作吗?

2 个答案:

答案 0 :(得分:0)

您可以将ConfirmationDialog组件设为类,并使用本地状态存储active变量:

import React, { Component, PropTypes } from 'react';

class ConfirmationDialog extends Component {
  constructor(props) {
    super(props);

    // Setting `active` state property from props.
    this.state = {
      active: props.active,
    };

    // As we are passing this function as event handler, we need bind context,
    // to get access to `this` inside this function.
    this.handleCloseClick = this.handleCloseClick.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    // When we will provide `active` variable via props, we will automatically set it to state.
    if (nextProps.active !== this.props.active) {
      this.setState({
        active: nextProps.active,
      });
    }
  }

  handleCloseClick() {
    // On clicking `close` button, setting `active` state variable to `false`,
    // it forces component to rerender with new state.
    this.setState({
      active: false,
    });
  }

  render() {
    const { title, size, message } = this.props;
    // Getting `active` variable from state, instead of props.
    const { active } = this.state;
    return (
      <Dialog
        active={active}
        title={title}
        type={size}
      >
        <p>{message}</p>
        <button onClick={this.handleCloseClick}>Close</button>
      </Dialog>
    );
  }
};

答案 1 :(得分:0)

您直接修改代码中的道具。我想知道这段代码是否有效。因为它不应该。

您需要将active内容存储在组件的某个位置,无论是这个还是(最有可能)位于上层组件。

而且看起来很简单,使用React, 。查看this tutorial,此处我将解释如何使用模式弹出窗口执行things like that