Conditional Rendering in React on button click

前端 未结 2 531
走了就别回头了
走了就别回头了 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 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(
            
    {this.state.buttonId === 1 && } {this.state.buttonId === 2 && } {this.state.buttonId !== 1 && this.state.buttonId !== 2 && } this.setButton(1)} value="Comic" type="button" ref="button" /> this.setButton(2)} value="Contest" ref="button1" type="button" />
    ); } } export default Head;

提交回复
热议问题