简体   繁体   English

如何避免 JSX 中的嵌套三元 ESLint 错误

[英]How to avoid nested ternary ESLint error in JSX

I have to do something like:我必须做类似的事情:

email ? do_this : icon ? do_that : do_something_else

This can be done very simple using nested ternary but this ESLint rule doesn't make this possible.这可以使用嵌套三元非常简单地完成,但是这个 ESLint 规则并不能做到这一点。

On their documentation they recommend to use if-else but I don't know how to implement this in my case在他们的文档中,他们建议使用 if-else 但我不知道如何在我的情况下实现它

The code works fine with one ternary.该代码适用于一个三元组。

return (
  <td>
    {email ? (
       <span>...</span>
     ) : (
       <span>...</span>
     )}
  </td>

adding nested ternary would return that ESLint error and using if-else says that if is an unexpected token:添加嵌套三元将返回该 ESLint 错误并使用 if-else 表示if是一个意外标记:

return (
  <td>
    {if(email) return ( <span>...</span>);
     else if(icon) return ( <span>...</span>);
     else return ( <span>...</span>);
     }
  </td>

Is it possible to solve this problem?有可能解决这个问题吗?

I find it useful to extract a complex functionality for readability:我发现提取复杂功能以提高可读性很有用:

import React from 'react';

// extracted functionality
const emailAction = (email, icon) => {
  if (email) {
    return <span>Do This</span>;
  } else {
    if (icon) {
      return <span>Do That</span>;
    } else {
      return <span>Do Something Else</span>;
    }
  }
};

// your Component
export const TableData = (props) => {
  return <td>{emailAction(props.email, props.icon)}</td>;
};

Another option is to use something like an enum to render:另一种选择是使用枚举之类的东西来呈现:

if (email) {
 content = 'email';
else if (icon) {
 content = 'icon';
} else {
 content = 'other';
}

return (
 <td>
   {{
   email: <span>...</span>,
   icon:  <span>...</span>,
   other: <span>...</span>,
   }[content]}
 </td>);

This is explained in more detail here: https://reactpatterns.js.org/docs/conditional-rendering-with-enum/这在这里更详细地解释: https://reactpatterns.js.org/docs/conditional-rendering-with-enum/

You can store the cell content in a variable:您可以将单元格内容存储在变量中:

let content;
if(email) {
  content = <span>...</span>;
} else if(icon) {
  content = <span>...</span>;
} else {
  content = <span>...</span>;
}

return <td>{content}</td>;

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

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