【问题标题】:How to add functional code inside the Render function - React JS如何在 Render 函数中添加功能代码 - React JS
【发布时间】:2023-01-09 19:57:24
【问题描述】:

下面是我的渲染逻辑,我试图在字段集中运行循环,但出现语法错误

Parsing error: '}' expected.eslint

请帮忙

  const renderComponentButtons = () => {
    const { questionNo } = componentContent;
    if (componentContent?.button) {
      return (
        <fieldset className="col-lg-8" aria-labelledby={componentContent?.ariaLabelledby}>
          {
            Object.keys(componentContent.button).map((key) => {
              <ButtonAction
                key={key}
                data-testid="getDisputeQst1"
                onClick={() => {
                  return (componentContent.button[key]?.displayModal === 'True')
                    ? openModalWindow(questionNo, key) : moveToNextQuestion(componentContent.button[key].buttonText);
                }}
              >
                {componentContent.button[key].buttonText}
              </ButtonAction>
            });
          }
        </fieldset>
      );
    }
    return null;
  };

【问题讨论】:

  • 您在哪一行看到错误? (此外,您不会从您的Object.keys(componentContent.button).map(...) 返回任何内容)

标签: reactjs


【解决方案1】:

您将 return null 替换为 return ""

 const renderComponentButtons = () => {
  const { questionNo } = componentContent;
  if (componentContent?.button) {
    return (
      <fieldset className="col-lg-8" aria-labelledby= 
         {componentContent?.ariaLabelledby}>
         {
          Object.keys(componentContent.button).map((key) => {
          <ButtonAction
          key={key}
          data-testid="getDisputeQst1"
          onClick={() => {
            return (componentContent.button[key]?.displayModal === 'True')
              ? openModalWindow(questionNo, key) : 
             moveToNextQuestion(componentContent.button[key].buttonText);
          }}
        >
          {componentContent.button[key].buttonText}
        </ButtonAction>
        });
       }
     </fieldset>
      ); 
     }
   return {foo:"bar"};
  };

【讨论】:

  • 这有什么帮助? (并且您的解释与您的代码不符)
【解决方案2】:

代码对我来说很好。但是,您缺少返回箭头函数内的组件。

return (&lt;ButtonAction&gt;{...}&lt;/ButtonAction&gt;)

就像现在一样,它返回undefined

如果您使用()=&gt;{},它将返回undefined,除非您使用return关键字。

但是您可以使用不带花括号的箭头函数,它将返回=&gt; 箭头之后的值。最佳做法是对返回值也使用圆括号

() =&gt; (&lt;ButtonAction/&gt;)

您也可以像这样返回对象

()=&gt;({foo:"bar"})

是相同的

()=&gt;{ return {foo:"bar"} }

也许值得您查看有关箭头功能的文档:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 2020-11-11
    • 2022-11-24
    • 1970-01-01
    • 2020-12-22
    • 2015-07-14
    • 2020-08-24
    • 2021-08-14
    相关资源
    最近更新 更多