admin管理员组

文章数量:1410725

I have three buttons that when clicking show and individual div but this is done in reactjs

import React, { Component } from 'react';

export class ModeExtended extends Component {

constructor() {
    super();

    this.busButton = this.busButton.bind(this);
    this.trainButton = this.trainButton.bind(this);
    this.tramButton = this.tramButton.bind(this);

    this.state = {
        isHidden: false,
    }
}


busButton(){
    console.log('Bus Button Was Pressed');
    this.setState((prevState) => {
        return{
            isHidden: !prevState.isHidden
        };
    });
}

trainButton(){
    console.log('Train Button Was Pressed');
    this.setState((prevState) => {
        return{
            isHidden: !prevState.isHidden
        };
    });
}

    tramButton(){
    console.log('Tram Button Was Pressed');
    this.setState((prevState) => {
        return{
            isHidden: !prevState.isHidden
        };
    });
}


render() {
    return (
        <div>   
            <h5>Mode Extended</h5>

            <button onClick={this.busButton}>Bus</button>
            <button onClick={this.trainButton}>Train</button>
            <button onClick={this.tramButton}>Tram</button>





            {this.state.isHidden && (
                <div>
                    <h6>You can show Bus Data Now....</h6>
                </div>
            )}

            {this.state.isHidden && (
                <div>
                    <h6>You can show Train Data Now....</h6>
                </div>
            )}

            {this.state.isHidden && (
                <div>
                    <h6>You can show Tram Data Now....</h6>
                </div>
            )}


        </div>
    )
}
}

export default ModeExtended

When I click any of the buttons it shows all bus, tram and train data - how do I get them to just show one thing at a time and making sure that the other states are closed. I am really missing something here and need a pointer or two or three…

How can I add an ID to make each button open separate from each other and when one is clicked how can I close the rest of the divs - or open state, I am so lost here. Please help me out.

Cheers as always!

Here is a REPL of my code:

I have three buttons that when clicking show and individual div but this is done in reactjs

import React, { Component } from 'react';

export class ModeExtended extends Component {

constructor() {
    super();

    this.busButton = this.busButton.bind(this);
    this.trainButton = this.trainButton.bind(this);
    this.tramButton = this.tramButton.bind(this);

    this.state = {
        isHidden: false,
    }
}


busButton(){
    console.log('Bus Button Was Pressed');
    this.setState((prevState) => {
        return{
            isHidden: !prevState.isHidden
        };
    });
}

trainButton(){
    console.log('Train Button Was Pressed');
    this.setState((prevState) => {
        return{
            isHidden: !prevState.isHidden
        };
    });
}

    tramButton(){
    console.log('Tram Button Was Pressed');
    this.setState((prevState) => {
        return{
            isHidden: !prevState.isHidden
        };
    });
}


render() {
    return (
        <div>   
            <h5>Mode Extended</h5>

            <button onClick={this.busButton}>Bus</button>
            <button onClick={this.trainButton}>Train</button>
            <button onClick={this.tramButton}>Tram</button>





            {this.state.isHidden && (
                <div>
                    <h6>You can show Bus Data Now....</h6>
                </div>
            )}

            {this.state.isHidden && (
                <div>
                    <h6>You can show Train Data Now....</h6>
                </div>
            )}

            {this.state.isHidden && (
                <div>
                    <h6>You can show Tram Data Now....</h6>
                </div>
            )}


        </div>
    )
}
}

export default ModeExtended

When I click any of the buttons it shows all bus, tram and train data - how do I get them to just show one thing at a time and making sure that the other states are closed. I am really missing something here and need a pointer or two or three…

How can I add an ID to make each button open separate from each other and when one is clicked how can I close the rest of the divs - or open state, I am so lost here. Please help me out.

Cheers as always!

Here is a REPL of my code:

Share Improve this question edited Dec 10, 2019 at 10:02 forkdbloke 1,5652 gold badges13 silver badges33 bronze badges asked Dec 10, 2019 at 8:18 Tired_ManTired_Man 971 silver badge15 bronze badges 3
  • 1 you should create two new states from the train and the tram ! – abdelhedi hlel Commented Dec 10, 2019 at 8:31
  • Thanks to everyone who left and answer and ment. Where can one learn more about state? – Tired_Man Commented Dec 10, 2019 at 9:46
  • 1 @user3502952 Make sure to check official docs from reactjs/docs/state-and-lifecycle.html – octobus Commented Dec 10, 2019 at 12:38
Add a ment  | 

4 Answers 4

Reset to default 6

You need to have 3 different isHidden properties to control your divs. You can do it like this:

this.state = {
    isHiddenBus: false,
    isHiddenTrain: false,
    isHiddenTram: false,
    }

and then in your render like this:

{this.state.isHiddenBus && (
                <div>
                    <h6>You can show Bus Data Now....</h6>
                </div>
            )}

            {this.state.isHiddenTrain && (
                <div>
                    <h6>You can show Train Data Now....</h6>
                </div>
            )}

            {this.state.isHiddenTram && (
                <div>
                    <h6>You can show Tram Data Now....</h6>
                </div>
            )}

also your buttons have to change to state accordingly to this.

busButton(){
    console.log('Bus Button Was Pressed');
    this.setState((prevState) => {
        return{
            isHiddenBus: !prevState.isHiddenBus
            isHiddenTram: false
            isHiddenTrain: false
        };
    });
}

trainButton(){
    console.log('Train Button Was Pressed');
    this.setState((prevState) => {
        return{
            isHiddenTrain: !prevState.isHiddenTrain
            isHiddenBus: false
            isHiddenTram: false

        };
    });
}

    tramButton(){
    console.log('Tram Button Was Pressed');
    this.setState((prevState) => {
        return{
            isHiddenTram: !prevState.isHiddenTram
            isHiddenTrain: false
            isHiddenBus: false
        };
    });
}

you can do somthing like this:

            import React, { Component } from 'react';

            export class ModeExtended extends Component {

            constructor() {
                super();

                this.state = {
                    curDivIndex:0,//currently visible div index
            //        isHidden: false,
                }
            }


            renderDiv=()=>{
                switch(this.state.curDivIndex){
                    case 1:return  <div>        <h6>You can show Bus Data Now....</h6>    </div>
                    case 2:return  <div>       <h6>You can show Train Data Now....</h6>   </div>
                    case 3:return  <div>       <h6>You can show Tram Data Now....</h6>   </div>
                }
                return null
            }
            setVisibleDiv=(index)=>{
                this.setState({curDivIndex:index})
            }

            render() {
                return (
                    <div>   
                        <h5>Mode Extended</h5>
                        <button onClick={()=>{this.setVisibleDiv(1)} }>Bus</button>
                        <button onClick={()=>{this.setVisibleDiv(2)}}>Train</button>
                        <button onClick={()=>{this.setVisibleDiv(3)}}>Tram</button>
                        {this.renderDiv()}
                    </div>
                )
            }
            }

            export default ModeExtended

EDIT

you want to have three different buttons, on click of each certain div needs to be visible. you can achieve this by maintaining the index of currently visible div. when user clicks any button you have to set the index of div to be visible which in the above code is achieved by using setVisibleDiv(index) call. and you can at rendering time use curDivIndex to decide visible div.

Or you can achieve this by declaring state properties for all case:

this.state = {
  hiddenBus: false,
  hiddenTrain: false,
  hiddenTram: false,
}

providing a name attribute to your buttons like so:

  <button name="hiddenBus" onClick={toggleDisplay}>Bus</button>
  <button name="hiddenTrain" onClick={toggleDisplay}>Train</button>
  <button name="hiddenBus" onClick={toggleDisplay}>Tram</button>

then by defining the toggleDisplay function to toggle their display:

toggleDisplay = (event) => {
  event.preventDefault(); // default behavior of a clicked button is to send a form so let's prevent this

  const { name } = event.target; // find the clicked button name value 

  this.setState((prevState => ({
    [name]: !prevState[name],
  }));
}

Setting[name] enables us to target the state prop via the nameattribute value and update it based on the previous state.

Try this

import React, { Component } from "react";

export default class Create extends Component {
  constructor(props) {
    super(props);

    this.state = {
      currentBtn: null
    };
  }
  clickedButton = e => {
    this.setState({ currentBtn: e.target.id });
  };
  showDivElem = () => {
    const { currentBtn } = this.state;
    switch (currentBtn) {
      case "A":
        return <div>A</div>;
        break;
      case "B":
        return <div>B</div>;
        break;
      case "C":
        return <div>C</div>;
        break;
      default:
        return <div>ABC</div>;
        break;
    }
  };
  render() {
    console.log(this.state.currentBtn);
    return (
      <div>
        <button id="A" onClick={e => this.clickedButton(e)}>
          A
        </button>
        <button id="B" onClick={e => this.clickedButton(e)}>
          B
        </button>
        <button id="C" onClick={e => this.clickedButton(e)}>
          C
        </button>
        {this.showDivElem()}
      </div>
    );
  }
}

本文标签: javascriptCreating show and hide sections with buttons in reactjsStack Overflow