隐藏所有div,并在单击多个按钮时显示一个div

时间:2019-05-19 08:02:25

标签: reactjs show-hide

我试图通过在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

我应该怎么做?

4 个答案:

答案 0 :(得分:2)

有很多模式可以实现“切换案例”,我将尝试展示我的最爱:

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

直进

管理每个组件的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

过滤子项

管理 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> ); 并将其用于过滤/映射子级。 检查React.Children API。

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>;
}
key = input()

def function(entry, key):
    length = len(entry)
    kk = key * (1 + length // len(key))   
    out = ""
    p = 0

    for i in entry:
        out += chr((ord(i)-97) % 26)

答案 1 :(得分:1)

我相信您正在寻找类似的东西。

要做的主要事情:

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

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

从“反应”导入React;

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;

答案 2 :(得分:1)

因此,基本上,您需要类似路由器的功能。这是一种方法:

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>
  }
}

答案 3 :(得分:0)

有很多方法可以解决此问题。但是我认为最好的解决方案是用一种简洁的方式解决问题的方法。 请在下面找到我尝试过的工作解决方案,该工作解决方案就像一种魅力:

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

希望这会有所帮助!