简体   繁体   English

将状态作为参数进行切换

[英]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. 我有多个值要显示在组件中,但一次只能显示1个值。 So in this case, valueOne is true, and I want to use it in a switch statement to return the value. 因此,在这种情况下, valueOne为true,我想在switch语句中使用它来返回值。 I will create a div to show the value. 我将创建一个div来显示值。

How do I pass the values from this.state as arguments in switch ? 如何将this.state的值作为参数传递给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. 我将添加一个回叫以关闭可见的div,并将在this.state中将该值设置为false,并将该值之后的值设置为true以在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} 在这里,我得到了let questOne = {this.state}的解析错误

Wrap the logic inside a function and call it from render 将逻辑包装在函数中,然后从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>
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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