如何在 React 组件中使用 switch 语句? [英] How to use switch statement inside a React component?

查看:51
本文介绍了如何在 React 组件中使用 switch 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 React 组件,在组件的 render 方法中,我有这样的东西:

render() {返回 (<div><div>//为简洁起见删除

{ 转变(...) {} }<div>//为简洁起见删除

);}

现在的重点是我有两个 div 元素,一个在顶部,一个在底部,它们是固定的.在中间我想要一个 switch 语句,并且根据我状态中的一个值,我想呈现一个不同的组件.所以基本上,我希望两个 div 元素总是固定的,并且每次都在中间渲染不同的组件.我正在使用它来实现多步骤付款程序).但是,正如目前的代码一样,它不起作用,因为它给了我一个错误,说 switch 是意外的.任何想法如何实现我想要的?

解决方案

试试这个,这也更简洁:在函数中从渲染中取出那个开关,然后调用它并传递你想要的参数.例如:

renderSwitch(param) {开关(参数){案例'富':返回酒吧";默认:返回富";}}使成为() {返回 (<div><div>//为简洁起见删除

{this.renderSwitch(param)}<div>//为简洁起见删除

);}

I have a React component, and inside the render method of the component I have something like this:

render() {
    return (
        <div>
            <div>
                // removed for brevity
            </div>

           { switch(...) {} }

            <div>
                // removed for brevity
            </div>
        </div>
    );
}

Now the point is that I have two div elements, one at the top and one at the bottom, that are fixed. In the middle I want to have a switch statement, and according to a value in my state I want to render a different component. So basically, I want the two div elements to be fixed always, and just in the middle to render a different component each time. I'm using this to implement a multi-step payment procedure). Though, as is the code currently it doesn't work, as it gives me an error saying that switch is unexpected. Any ideas how to achieve what I want?

解决方案

Try this, which is way cleaner too: Get that switch out of the render in a function and just call it passing the params you want. For example:

renderSwitch(param) {
  switch(param) {
    case 'foo':
      return 'bar';
    default:
      return 'foo';
  }
}

render() {
  return (
    <div>
      <div>
          // removed for brevity
      </div>
      {this.renderSwitch(param)}
      <div>
          // removed for brevity
      </div>
    </div>
  );
}

这篇关于如何在 React 组件中使用 switch 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆