【问题标题】:Maintain initial state of a form保持表单的初始状态
【发布时间】:2019-09-06 06:29:30
【问题描述】:

在学习反应时,我制作了菜单并在菜单上单击我打开了一个表单。我想在表单上有一个“关闭”图标,按下该图标会关闭表单,然后再次在菜单上单击将其打开。

我创建了一个处理表单状态的父组件(子组件)。它管理 showchild = true 或 false。

//this is button defined on form compenent
 <button onClick={this.props.onClose}>Self Close</button>


//this is parent component
import React from 'react';
import DemoForm from './form';

class ParentComponent extends React.Component {
    closeChild = () => {
      this.setState({
        showChild: false,
      });
    };

 constructor(props) {
      super(props);
      this.state = {
        showChild: true
      };
    }
   render() {
      return (
        <div>
          {this.state.showChild && <DemoForm onClose={this.closeChild} />}
        </div>
      );
    }
  }

export default ParentComponent;

这很好用,单击按钮时表单关闭,我检查了反应,表单的状态从 showchild true 变为 false。问题是下次我尝试单击菜单打开此表单时,表单无法打开。因为 showchild 的状态 = false。

一旦表单最终关闭或任何其他技术,我们可以将表单的状态更改为 showchild = true 吗?

我怎样才能做到这一点?我仍在反应,redux 是下一个目标。我可以通过反应状态管理来做到这一点吗?

【问题讨论】:

  • 能否给出打开表单的逻辑代码?
  • 从 react-router-dom 很简单

标签: reactjs state


【解决方案1】:

您只需将 closeChild() 函数更改为 triggerMenu(),这样当它打开时它会关闭,当它关闭时它会打开:

    triggerMenu = () => {
        this.setState((prevState) => {
            showChild: !prevState.showChild
        })
    };

【讨论】:

  • @Phillip 是的,对不起,我错过了。编辑解答,谢谢
  • closeChild = () =&gt; { this.setState(prevState =&gt; ({ showChild : !prevState.showChild })); }; 我这样做了,但还是一样,第二次无法打开表单。
  • @RanuVijay 应该可以工作,确保你将onCloseonClick 都指向closeChild。因为这段代码是从true to falsefalse to true更新状态
  • @ErtanHasani 当我点击按钮后检查反应开发工具以了解表单状态时,它显示“showChild:false”,这就是我无法第二次打开它的原因。跨度>
  • ` 来自父组件的 from form and ` 已经指向 closeChild
猜你喜欢
  • 1970-01-01
  • 2021-06-15
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 2017-08-25
  • 2012-08-10
  • 2013-03-27
相关资源
最近更新 更多