Conditional Rendering in React on button click

前端 未结 2 530
走了就别回头了
走了就别回头了 2020-12-22 05:59

I want to conditional render component on button click, I wrote the following code but it\'s not working, when I click on comic, the comic component should be loaded, and wh

相关标签:
2条回答
  • 2020-12-22 06:51

    Your .render must return the components that you want to show.

    So the code should look something like --

    let component = this.state.buttonId === 2 ? <Contest/> : <Comic/>
    
    return(
        <>
            {component}
            <div>
                {/* your button here */}      
            </div>
        </>
    );
    
    0 讨论(0)
  • 2020-12-22 07:02

    You are not returning your components, try the following:

    class Head extends Component{
        constructor(){
            super();
            this.state = {
             buttonId: null
            }
            this.setButton = this.setButton.bind(this);
          }
          setButton(id){
            this.setState({buttonId: id});
          }
        render(){
            return(
            <div>
                 {this.state.buttonId === 1 && <Comic/>}
                 {this.state.buttonId === 2 && <Contest/>}
                 {this.state.buttonId !== 1  && this.state.buttonId !== 2 && <Comic/>}
                 <input className={this.state.buttonId === 1? "button1 orange" : 
                  "button1"} onClick={() => this.setButton(1)} value="Comic" 
                   type="button" ref="button" />
                <input className={this.state.buttonId === 2? "button2 orange" : 
                "button2"} onClick={() => this.setButton(2)}  value="Contest" 
                 ref="button1" type="button" />
    
             </div>
             );
           }
        }
    
    export default Head;
    
    0 讨论(0)
提交回复
热议问题