简体   繁体   English

用新的onClick替换默认组件

[英]React replacing the default component with new one onClick

I need to achieve an task in my project. 我需要在我的项目中完成一项任务。 In that, I have a default component in the homepage, it will render everytime the page loads, by default. 在那里,我在主页中有一个默认组件,默认情况下,它会在每次页面加载时呈现。 In that Component, i have four buttons or div's in the top and an Register button in the bottom. 在该组件中,我在顶部有四个按钮或div,在底部有一个Register按钮。 Now, when the user clicks an button or div in the top, it should pick a component assigned to that button and it should replace the default with the picked one, when the user clicks the Register button in the button. 现在,当用户单击顶部的按钮或div时,它应该选择分配给该按钮的组件,并且当用户单击按钮中的“注册”按钮时,它应该用所选择的组件替换默认值。 Below, is my code. 下面是我的代码。 Its not completed properly. 它未正确完成。 Please let me know the way, by which i can achieve the desired output. 请让我知道我可以通过哪种方式获得所需的输出。

Thanks in advance. 提前致谢。

class GetStart extends Component {

        constructor(props){
        super(props);
        this.state = {
            value: null,
        };
        };

      handleEvent = (button) => {
        this.setState({ value: button });
      };
        handleClick = () => {

        } ;

      render() {
          const { classes } = this.props;
          const { value } = this.state;
        return (
            <div>
                    <div className={classes.buttonComponent}>
                        <Button onClick={() => this.handleEvent(0)}>Component One</Button>
                        <Button onClick={() => this.handleEvent(1)}>Component Two</Button>
                        <Button onClick={() => this.handleEvent(2)}>Component three</Button>
                        <Button onClick={() => this.handleEvent(3)}>Component Four</Button>

                        <Button variant="contained" onClick={this.handleClick} className={classes.submitButton}>
                            Register Now
                        </Button>
                    </div>
            switch(value){
               case 0: 
                 return <ComponentOne />;
               case 1:
                 return <ComponentTwo />;
               case 2:
                 return <ComponentThree />;
               case 3:
                 return <ComponentFour />;
               else:
                  return <DefaultComponent />;
                   }
                </div>
        );  
      }
    }



    export default GetStart;

You can't do a switch case inside the return . 你不能在return做一个开关案例。 You will have to do it outside of it. 你必须在它之外做。 Can you try this? 你能试试吗?

render() {
    const { classes } = this.props;
    const { value } = this.state;
    let component;
    switch (value) {
      case 0:
        component = <ComponentOne />;
        break;
      case 1:
        component = <ComponentTwo />;
        break;
      case 2:
        component = <ComponentThree />;
        break;
      case 3:
        component = < ComponentFour />;
        break;
      default:
        component =  <DefaultComponent />;
        break;
    }
    return (
      <div>
        <div className={classes.buttonComponent}>
          <Button onClick={() => this.handleEvent(0)}>Component One</Button>
          <Button onClick={() => this.handleEvent(1)}>Component Two</Button>
          <Button onClick={() => this.handleEvent(2)}>Component three</Button>
          <Button onClick={() => this.handleEvent(3)}>Component Four</Button>

          <Button variant="contained" onClick={this.handleClick} className={classes.submitButton}>
            Register Now
          </Button>
        </div>
        {
          component
        }
      </div>
    )
  }

You cannot have a Switch statement within render return statement. 您不能在render return语句中使用Switch语句。 You can instead have it in the render and assign the correct component to a variable and render it like below 您可以在渲染中使用它并将正确的组件分配给变量并像下面一样渲染它

render() {
  const { classes } = this.props;
  const { value } = this.state;
  let Comp;
  switch(value){
         case 0: 
           Comp =  ComponentOne;
         case 1:
           Comp =  ComponentTwo;
         case 2:
           Comp =  ComponentThree;
         case 3:
           Comp =  ComponentFour;
         else:
            Comp = DefaultComponent;
  }
  return (
      <div>
              <div className={classes.buttonComponent}>
                  <Button onClick={() => this.handleEvent(0)}>Component One</Button>
                  <Button onClick={() => this.handleEvent(1)}>Component Two</Button>
                  <Button onClick={() => this.handleEvent(2)}>Component three</Button>
                  <Button onClick={() => this.handleEvent(3)}>Component Four</Button>

                  <Button variant="contained" onClick={this.handleClick} className={classes.submitButton}>
                      Register Now
                  </Button>
              </div>
              <Comp />
          </div>
  );  
}

The above is however not the best way to do this and I would recommend you to go though react-router and use it for rendering conditional components. 然而,上面不是最好的方法,我建议你通过react-router并使用它来渲染条件组件。 You can make use of MemoryRouter from react-router if you don't want to update the URL with the path assigned to each Route 如果您不想使用分配给每个Route的路径更新URL,则可以使用react-routerMemoryRouter

I think you will need two state variables. 我想你需要两个状态变量。 One will hold the final value of component to render, and the other will be used to track the events as you click the buttons. 一个将保持要渲染的组件的最终值,另一个将用于在单击按钮时跟踪事件。

class GetStart extends Component {

constructor(props) {
    super(props);
    this.state = {
        value: null,
        componentToRender: null //tells switch which component to render
    };
    this.renderComponent = this.renderComponent.bind(this)
};

handleEvent = (button) => {
    this.setState({value: button});
};
handleClick = () => {
    this.setState({componentToRender: this.state.value})//take the
    // currently selected component and make it the component to render
};
    //extract the switch statement to a method of its own
renderComponent() {
    switch (this.state.componentToRender) {
        case 0:
            return <ComponentOne/>;
        case 1:
            return <ComponentTwo/>;
        case 2:
            return <ComponentThree/>;
        case 3:
            return <ComponentFour/>;
        default://replaced 'else' with 'default'
            return <DefaultComponent/>;
    }
}

render() {
    const {classes} = this.props;
    return (
        <div>
            <div className={classes.buttonComponent}>
                <Button onClick={() => this.handleEvent(0)}>Component
                    One</Button>
                <Button onClick={() => this.handleEvent(1)}>Component
                    Two</Button>
                <Button onClick={() => this.handleEvent(2)}>Component
                    three</Button>
                <Button onClick={() => this.handleEvent(3)}>Component
                    Four</Button>

                <Button variant="contained" onClick={this.handleClick}
                        className={classes.submitButton}>
                    Register Now
                </Button>
            </div>
            {this.renderComponent()}
        </div>
    );
   }
  }


  export default GetStart;

As others have mentioned, you are not able to make use of a switch statement in JSX like that. 正如其他人所提到的,你无法在JSX中使用switch语句。

Your code will be easier to understand if you seperate out parts of you logic into different functions. 如果将部分逻辑分离到不同的函数中,您的代码将更容易理解。

I've created a Code Sandbox that has your required functionality to help get you started: https://codesandbox.io/s/zr766pkwpp 我创建了一个Code Sandbox,它具有帮助您入门所需的功能: https//codesandbox.io/s/zr766pkwpp

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

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