reactjs - 如何在对话框组件之外处理对话框状态?

标签 reactjs

我有以下对话框组件:

class LoginDialog extends React.Component {
  state = {
    open: false,
  };

  openDialog = () => {
    this.setState({ open: true });
  };

  handleClose = () => {
    this.setState({ open: false });
  };

  render() {
    return (
      <div>
        <Dialog
          open={this.state.open}
          onClose={this.handleClose}
        >
          <DialogActions>
            <Button onClick={this.handleClose} color="primary">
              Cancel
            </Button>
            <Button onClick={this.handleClose} color="primary">
              Subscribe
            </Button>
          </DialogActions>
        </Dialog>
      </div>
    );
  }
}

如何从父组件打开该对话框并确保关闭对话框也能正常工作?这是我的尝试

class MainAppBar extends React.Component {
    state = {
    openLoginDialog: false,
    openRegisterDialog: false
    };
    render() {
        return (
            <div>
                <Button color="inherit" onClick={this.state.openLoginDialog}>Login</Button>
                )}
                <LoginDialog /*not sure how to pass here openLoginDialog*//>
            </div>
        );
    }
}

所以我不确定我是否真的必须在子/父中保留对话框状态以及如何从父中正确打开它。

最佳答案

无论登录对话框在父级中是否打开,您都必须维护状态。将打开/关闭状态传递给子级,并通过 props 将关闭对话框的回调传递给子级。

class MainAppBar extends React.Component {
  state = {
    openLoginDialog: false,
    openRegisterDialog: false
  };

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

  closeLoginDialog = () => {
    this.setState({
      openLoginDialog: false
    });
  };
  render() {
    return (
      <div>
        <Button color="inherit" onClick={() => this.openLoginDialog()}>
          Login
        </Button>
        )}
        <LoginDialog
          closeLoginDialog={this.closeLoginDialog}
          isLoginDialogOpen={this.state.openLoginDialog}
        />
      </div>
    );
  }
}

该组件不需要任何状态管理,因为我们在父组件中管理它。我们可以这样纯:

const LoginDialog = props => (
  <div>
    <Dialog open={props.isLoginDialogOpen} onClose={props.closeLoginDialog}>
      <DialogActions>
        <Button onClick={props.closeLoginDialog} color="primary">
          Cancel
        </Button>
        <Button onClick={props.closeLoginDialog} color="primary">
          Subscribe
        </Button>
      </DialogActions>
    </Dialog>
  </div>
);

希望这对您有帮助!

关于reactjs - 如何在对话框组件之外处理对话框状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56174721/

相关文章:

reactjs - JSX 中的混合运算符

javascript - 使用 div 的两种方式数据绑定(bind)

javascript - 在 React.js 中向下滚动页面时如何加载更多搜索结果?

reactjs - 尽管使用了 useEffect,React 数组并未更新

reactjs - 如何在 Material ui core 3.9.2 中使用 InputRef

javascript - 绘图范围不限于 x 轴,绘制整个图表

javascript - 类型错误 : Cannot destructure property 'jobArray' of 'react__WEBPACK_IMPORTED_MODULE_0__.state' as it is undefined

Javascript 数组不会在 componentDidMount 之外更新

javascript - 如何将连接、组件和功能导出到一处? (只需要建议)

javascript - 以编程方式触发点击