【问题标题】:Hide all div and show one div on clicking multiple button隐藏所有 div 并在单击多个按钮时显示一个 div
【发布时间】:2019-05-19 08:02:25
【问题描述】:

我试图通过在一个 div 上隐藏/显示来将 3 个组件放在一个页面中。但我并没有真正了解如何做到这一点。这是第一个 div。

<div>
                        <p>What is the type of your property?</p>
                        <button >Residence</button>

                        <button>Commercial</button>

                        <span style={{background:'transparent', border:'0', fontSize:'16px',color:'#ef3530'}}>Back</span>

                        <span style={{background:'transparent', border:'0', fontSize:'16px',color:'#ef3530'}}>Next</span>

                    </div>

只有当我点击“商业”或“下一步”按钮时,它才会进入第二个 div,而第一个 div 会隐藏。

<div>
                    <p>What is the type of your commercial property?</p>

                    <button>Office</button>

                    <button>Restaurant</button>

                    <button >Outlet</button>
                    <span style={{background:'transparent', border:'0', fontSize:'16px',color:'#ef3530'}}>Back</span>

                    <span style={{background:'transparent', border:'0', fontSize:'16px',color:'#ef3530'}}>Next</span>
                </div>

最后,如果我从第一个 div 和第二个 div 的任何按钮(除了后退按钮)单击“餐厅”按钮,它将进入第三个 div,其他 div 将隐藏。这是第三个 div。

<div>

            <div className='slider'  style={{ marginTop:'165px',marginLeft:'319px',width:'700px',backgroundColor:'EF5350'}} >

                <Slider min={850} max={5000} value={value} onChangeStart={this.handleChangeStart}
                    onChange={this.handleChange}
                    onChangeComplete={this.handleChangeComplete}
                />
                <div className='value'>{value} Squarefeet</div>
                <div style={{marginTop:'86px'}}>



                        <span onChange={this.handleChange} onClick={() => this.saveValue()} >Next</span>
                       <span onChange={this.handleChange} onClick={() => this.saveValue()} >Next</span>

                </div>

            </div>
    </div>

我试图这样做。但它不会起作用。

import React from 'react';
import Link from "next/link";
class Jh extends React.Component {
    constructor() {
        super();
        this.state = {
            shown: true,
            hide: false
        };
    }

    toggle() {
        this.setState({
            shown: !this.state.shown
        });
    }

    toggles() {
        this.setState({
            shown: !this.state.hide
        });
    }

    render() {
        var shown = {
            display: this.state.shown ? "block" : "none"
        };

        var hidden = {
            display: this.state.shown ? "none" : "block"
        }

        return (
            <div>
                <button onClick={this.toggle.bind(this)} style={ shown }>
                    <div>
                        <p>What is the type of your property?</p>
                        <button >Residence</button>

                        <button>Commercial</button>

                        <span style={{background:'transparent', border:'0', fontSize:'16px',color:'#ef3530'}}>Back</span>

                        <span style={{background:'transparent', border:'0', fontSize:'16px',color:'#ef3530'}}>Next</span>

                    </div>



                </button>

                <button onClick={this.toggles.bind(this)} style={ hidden }>
                    <div>
                        <p>What is the type of your commercial property?</p>

                        <button>Office</button>

                        <button>Restaurant</button>

                        <button >Outlet</button>
                        <span style={{background:'transparent', border:'0', fontSize:'16px',color:'#ef3530'}}>Back</span>

                        <span style={{background:'transparent', border:'0', fontSize:'16px',color:'#ef3530'}}>Next</span>
                    </div>
                </button>

            </div>
        )
    }
}
export default Jh

我的方法应该是什么?

【问题讨论】:

  • 刚刚更新了我的沙箱,如果我的解决方案对您有帮助,请告诉我!很高兴回答任何问题。我花了很多时间试图自己解决这个问题哈哈。
  • 它几乎符合我想要的。它只是当我从第一页选择“餐厅”按钮时,我希望它呈现到第三个 div“这是你的业务”。否则每个要求都匹配。我创建了另一个仅适用于餐厅的功能并将其增加 2。感谢您的努力
  • 太棒了!我很高兴这对你有用并且你想通了。

标签: reactjs show-hide


【解决方案1】:

有很多模式可以实现“switch case”,我会尝试展示我的最爱:

为了简单起见,我将使用通用用例。

直截了当

管理每个组件的visible 状态:

return {visible && <CoolComponent id={1} />};

变相切换大小写

管理对象键的状态。 (currentCounter)

const countersPicker = {
  counter1: <Counter id={1} />,
  counter2: <Counter id={2} />,
  coolComponent:  <CoolComponent id={3} />
};

  return {countersPicker[currentCounter]};

这里你还可以对对象进行操作,例如,添加标题:

  return {Object.entries(countersPicker).map(([key,component]) => 
    <div key={key}>
      <h1>Component key = {key}</h1>
      {component}
    </div> 
  )};

过滤子项

管理predicate 并将其用于过滤/映射子项。 检查React.Children API。

  return (
    <FilterComponents predicate={predicate}>
      <Counter key={1} id={1} />
      <Counter key={2} id={2} />
      <CoolComponent key={3} id={3} />
      <BestComponent key={4} id={4} />
    </FilterComponents>
);
function FilterComponents({ children, predicate }) {
  const filteredChildren = React.Children.toArray(children).filter(child =>
    // Use the predicate.
    // Filter a child by key, key & type or even use ref etc.
  );
  return <div>{filteredChildren}</div>;
}

【讨论】:

    【解决方案2】:

    我相信您正在寻找这样的东西。

    主要要做的事情:

    提高你的状态价值。使用数组按顺序跟踪不同的页面。跟踪当前页面。跟踪集合的开始和结束。

    这里也是沙盒:https://codesandbox.io/s/unruffled-sun-gpzx6

    从“反应”导入反应;

    class Pages extends React.Component {
      state = {
        currentPage: "property",
        pages: ["property", "type", "firstBusiness"],
        start: true,
        end: false
      };
    
      changePage = event => {
        const { currentPage, pages } = this.state;
        const { name } = event.target;
        //check if we are going to end
        if (
          name == "next" &&
          pages[pages.indexOf(currentPage) + 1] === pages[pages.length - 1]
        ) {
          this.setState({
            currentPage: pages[pages.indexOf(currentPage) + 1],
            end: true,
            start: false
          });
          //go to next page
        } else if (name == "next") {
          this.setState({
            currentPage: pages[pages.indexOf(currentPage) + 1],
            start: false
          });
          //check if we are going to beginning
        } else if (
          name == "back" &&
          currentPage !== pages[0] &&
          pages[pages.indexOf(currentPage) - 1] == pages[0]
        ) {
          this.setState({
            currentPage: pages[pages.indexOf(currentPage) - 1],
            start: true
          });
          //go back one page
        } else {
          this.setState({
            currentPage: pages[pages.indexOf(currentPage) - 1],
            end: false
          });
        }
      };
    
      goToNextPage = () => {
        const { currentPage, pages, end } = this.state;
        //check if we are going to end
        if (pages[pages.indexOf(currentPage) + 1] === pages[pages.length - 1]) {
          this.setState({
            currentPage: pages[pages.indexOf(currentPage) + 1],
            end: true,
            start: false
          });
          //go to next page
        } else if (end) {
          return;
        } else {
          this.setState({
            currentPage: pages[pages.indexOf(currentPage) + 1],
            start: false
          });
        }
      };
    
      render() {
        const { currentPage, start, end } = this.state;
        return (
          <div style={{ background: "gray" }}>
            {currentPage === "property" ? (
              <div>
                <p>What is the type of your property?</p>
                <button onClick={this.goToNextPage}>Residence</button>
                <button onClick={this.goToNextPage}>Commercial</button>
              </div>
            ) : null}
    
            {currentPage === "type" ? (
              <div>
                <p>What is the type of your commercial property?</p>
                <button onClick={this.goToNextPage}>Office</button>
                <button onClick={this.goToNextPage}>Restaurant</button>
                <button onClick={this.goToNextPage}>Outlet</button>
              </div>
            ) : null}
    
            {currentPage === "firstBusiness" ? (
              <div>
                <p>Is this your first business?</p>
                <button onClick={this.goToNextPage}>Yes</button>
                <button onClick={this.goToNextPage}>No</button>
              </div>
            ) : null}
    
            <div>
              <button onClick={this.changePage} name="back" disabled={start}>
                Back
              </button>
              <button onClick={this.changePage} name="next" disabled={end}>
                Next
              </button>
            </div>
          </div>
        );
      }
    }
    
    export default Pages;
    

    【讨论】:

    • 你可以使用&amp;&amp;, currentPage === "property" &amp;&amp; &lt;Component/&gt;
    【解决方案3】:

    所以本质上你想要类似路由器的功能。这是一种方法:

    class FirstPage extends React.Component {
      render() {
        //...first page content
      }
    }
    
    class SecondPage extends React.Component {
      render() {
        //...second page content
      }
    }
    
    const pages = {
      first: FirstPage,
      second: SecondPage
    };
    
    class App extends React.Component {
      constructor() {
        this.state = {
          page: 'first'
        };
      }
    
      render() {
        const PageComponent = pages[this.state.page];
    
        return <div>
          <button onClick={() => this.setState({page: 'first'})}>First page</button>
          <button onClick={() => this.setState({page: 'second'})}>Second page</button>
    
          <PageComponent/>
        </div>
      }
    }
    

    【讨论】:

      【解决方案4】:

      有很多方法可以解决这个问题。但在我看来,最好的解决方案是以简洁的方式解决问题。 请在下面找到我尝试过的有效解决方案:

      import React from "react";
      
      class Pages extends React.Component {
        state = {
          activeTab: 1
        };
        toggle = tab => {
          this.setState({
            activeTab: tab
          });
        };
        togglePage = page => {
          if (page === "next") {
            this.setState({
              activeTab: this.state.activeTab + 1
            });
          } else if (page === "back") {
            this.setState({
              activeTab: this.state.activeTab - 1
            });
          }
        };
      
        render() {
          return (
            <div style={{ background: "#dedede" }}>
              <div hidden={this.state.activeTab === 1 ? false : true}>
                <p>1) What is the type of your property?</p>
                <button class="btn btn-primary" onClick={() => this.toggle(2)}>
                  Residence
                </button>
                <button onClick={() => this.toggle(2)}>Commercial</button>
              </div>
      
              <div hidden={this.state.activeTab === 2 ? false : true}>
                <p>2) What is the type of your commercial property?</p>
                <button onClick={() => this.toggle(3)}>Office</button>
                <button onClick={() => this.toggle(3)}>Restaurant</button>
                <button onClick={() => this.toggle(3)}>Outlet</button>
              </div>
      
              <div hidden={this.state.activeTab === 3 ? false : true}>
                <p>3) Is this your first business?</p>
                <button onClick={this.NextAction}>Yes</button>
                <button onClick={this.NextAction}>No</button>
              </div>
      
              <div>
                <button
                  onClick={() => this.togglePage("back")}
                  name="back"
                  disabled={this.state.activeTab === 1 ? true : false}
                >
                  Back
                </button>
                <button
                  onClick={() => this.togglePage("next")}
                  name="next"
                  disabled={this.state.activeTab === 3 ? true : false}
                >
                  Next
                </button>
              </div>
            </div>
          );
        }
      }
      
      export default Pages;
      

      在 react 中,我们有一个 hidden 属性,您可以使用它来显示/隐藏元素,而无需为此编写任何 css。 而且我已经尝试用最少的变量来解决这个问题。

      可以在此处找到相同的沙箱:https://codesandbox.io/s/mysolution-g8fu6

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-22
        • 2013-04-21
        • 2015-10-15
        • 2016-11-27
        • 2020-02-23
        • 2021-06-14
        • 1970-01-01
        相关资源
        最近更新 更多