点击多个按钮后隐藏所有 div 并显示一个 div

3

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

我的应对方式应该是什么?


1
我刚刚更新了我的沙盒,请告诉我我的解决方案是否对你有帮助!很高兴回答任何问题。我自己花了很多时间来尝试解决这个问题,哈哈。 - Chris Ngo
1
它几乎符合我的要求。只是当我从第一页选择“餐厅”按钮时,我希望它呈现在第三个div中的“这是您的业务吗”。否则,每个要求都匹配。我为仅餐厅创建了另一个函数,并将其增加了2。感谢您的努力。 - ariful Islam
太棒了!我很高兴那对你有用并且你解决了它。 - Chris Ngo
4个回答

2

有许多模式可以实现"switch case",我将尝试展示我最喜欢的:

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

直接

管理每个组件的visible状态:

最初的回答

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

伪装成switch case的语句

管理对象键的状态(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>;
}


1

我相信你正在寻找这样的内容。

主要任务:

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

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

import React from "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;

你可以只使用 &&currentPage === "property" && <Component/> - Dennis Vash

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

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 希望这能帮到你!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接