简体   繁体   中英

Pass state as arguments to switch

I have multiple values to show in the component, but only 1 value is to be displayed at a time. So in this case, valueOne is true, and I want to use it in a switch statement to return the value. I will create a div to show the value.

How do I pass the values from this.state as arguments in switch ?

Is this the proper way to do it? I cannot use ternary operator cause I may have more than 2 values. I will add a call back to close the visible div and will make that value false in this.state and make the one after that true to be listed in the DOM. But how do I do that?

import React, { Component } from 'react';

    const one = () => {
        return(
            <div>
                <p> This is One</p>
            </div>
        )
    }

    class Component extends React.Component{
       state = {
         value: 'one'
    }

    renderSelected = () => {
      switch(this.state.value){
        case 'one' : return <div>{one}</div>
        default : return null
      }
    }

    render(){
      return <div className='main'>{this.renderSelected()}</div>
    }
}

export default MyComp;

Here I get a parsing error for let questOne = {this.state}

Wrap the logic inside a function and call it from render

class Component extends React.Component{
    state = {
        value: 'one'
    }

    renderSelected = () => {
        switch(this.state.value){
            case 'one' : return <div>1</div>
            default : return null
        }
    }

    render(){
        return <div className='main'>{this.renderSelected()}</div>
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM