简体   繁体   English

有条件地在反应中渲染内容

[英]Conditionally rendering content in react

I am having a functional component that takes two items as props.我有一个功能组件,它需要两个项目作为道具。 The values of each properties could be undefined , "" , null , "null" , or a valid string (for example, "test" ).每个属性的值可以是undefined""null"null"或有效字符串(例如"test" )。

I need to conditionally render these props based on values我需要根据值有条件地渲染这些道具

if prop1 and prop2 are both present then it should display as prop1(prop2) , if either one of them are present then it should either be prop1 or just prop2 .如果prop1prop2都存在,那么它应该显示为prop1(prop2) ,如果其中任何一个存在,那么它应该是prop1或只是prop2 In case both of them are not present then should display "Not Available".如果它们都不存在,则应显示“不可用”。 Only valid strings should be taken.只应采用有效字符串。 If values has either undefined , "" , null , "null" it should not be displayed.如果值具有undefined""null"null" ,则不应显示。

I am having trouble building up the logic.我在建立逻辑时遇到了麻烦。 This is what I have tried.这是我尝试过的。

const Test = (props) => {
   let { prop1, prop2 } = props;
    let content: string;
    if ((!prop1 || prop1 === "null") && (!prop2 || prop2 === "null")) {
        content = "Not Available";
    } else if (!!prop1 && !!prop2) {
        content = `${prop1} (${prop2})`;
    } else {
       content = `${prop1 || prop2}`;
    }
   
  return (
    <>
      {content}
    </>
  );

}

This maybe one way to achieve the desired objective:这可能是实现预期目标的一种方法:

const isPropInvalid = inp => [undefined, null, '', ' '].includes(inp);

const content = isPropInvalid(prop1)
  ? isPropInvalid(prop2) ? 'Not Available' : prop2
  : isPropInvalid(prop2) ? prop1 : `${prop1} (${prop2})`

Explanation解释

  • set-up an array with elements that are considered 'invalid' (ie, undefined, null, '', 'null')使用被认为是“无效”的元素设置一个数组(即未定义,null,“”,“空”)
  • use simple if-else or ?: ternary-operators to assign the appropriate value to content based on whether one or both props are invalid.使用简单的 if-else 或?:三元运算符根据一个或两个道具是否无效为content分配适当的值。

Code Snippet代码片段

 const isPropInvalid = inp => [undefined, null, '', 'null'].includes(inp); const content = (prop1, prop2) => isPropInvalid(prop1)? isPropInvalid(prop2)? 'Not Available': prop2: isPropInvalid(prop2)? prop1: `${prop1} (${prop2})`; console.log(content('abc', 'xyz')); console.log(content()); console.log(content(null, 'xyz')); console.log(content('abc', 'null'));

How about a separate function that returns whether or not the value is valid?一个单独的 function 返回值是否有效怎么样?

function propIsValid(value) {
  // valid if truthy and not "null" (string)
  return !!prop && value != "null";
}

The above checks for a thuthy value, which means that all falsy values are considered invalid.上面检查了一个 thuthy 值,这意味着所有 falsy 值都被认为是无效的。 This includes null , undefined and "" , but also false , NaN and 0 .这包括nullundefined"" ,还包括falseNaN0 Which might or might not be a problem, depending on your context.这可能是也可能不是问题,具体取决于您的上下文。

If you want a more target approach you could use the following:如果您想要一个更有针对性的方法,您可以使用以下方法:

const invalid = [undefined, null, "", "null"];
return !invalid.includes(value);

Then simplify your component to:然后将您的组件简化为:

const Test = ({ prop1, prop2 }) => {
  const allValid   = [prop1, prop2].every(propIsValid);
  const firstValid = [prop1, prop2].find(propIsValid);

  if (allValid) {
    return <>{prop1}({prop2})</>;
  } else if (firstValid) {
    return <>{firstValid}</>;
  } else {
    return <>Not Available</>;
  }
}

This uses every() to check if both are valid, but this could also be written as propIsValid(prop1) && propIsValid(prop2) .这使用every()来检查两者是否有效,但这也可以写为propIsValid(prop1) && propIsValid(prop2) find() is used to find the first valid value (if any), this does assume that a valid value is always thuthy . find()用于查找第一个有效值(如果有),这确实假定有效值始终为thuthy

I guess this is a tricky condition by itself, so I wouldn't worry too much if it looks a bit weird.我想这本身就是一个棘手的条件,所以如果它看起来有点奇怪,我不会太担心。 One think you can do tho is to organize the component code in variables and smaller functions like so:一种认为您可以做的是将组件代码组织在变量和较小的函数中,如下所示:

const isDefined = (value) => value !== "null" && !!value
const buildString = (prop1, prop2) => {
  let string = prop1 || prop2
  return prop1 && prop2
    ? `${string} (${prop2})`
    : string
}

const Test = ({ prop1, prop2 }) => {
  const someDefined = isDefined(prop1) || isDefined(prop2);
   
  return (
    <>
      {!someAreDefined && "Not Available"}
      {someAreDefined && buildString(prop1, prop2)}
    </>
  );
}

I think that helps a lot with readability and understanding the flow and possible outputs for this component.我认为这对可读性和理解该组件的流程和可能的输出有很大帮助。

Just use a ternary只需使用三元

(prop1 && !/null/.test(prop1)) && (prop2 && !/null/.test(prop2)) ? `${prop1}(${prop2})` : prop1 && !/null/.test(prop1) ? `${prop1}` : prop2 && !/null/.test(prop2) ? `${prop2}` : 'Not Available';

Since undefined "" and null are falsey in nature it will only use regex to test for the pattern null if it needs to.由于 undefined "" 和 null 本质上是错误的,因此它只会在需要时使用正则表达式来测试模式 null。 If there are any other values that you want to be considered invalid, just add them to the regex.如果您希望将任何其他值视为无效,只需将它们添加到正则表达式。

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

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