【问题标题】:How to get this value in a variable and use it in a conditional in React?如何在变量中获取此值并在 React 中的条件中使用它?
【发布时间】:2021-08-14 02:02:11
【问题描述】:

如果能帮我解决这个问题,我将不胜感激。在下面的代码中,我想从 span 中获取 `` 之间的值并将它们分配给一个变量,以便具有以下逻辑:

${research.data.codesRelated[1].code} === undefined 
  ? ${research.data.description} 
  : ${research.data.codesRelated[1].code} ${research.data.description}

我该怎么做?看起来很简单,但我无法解决,不知道在哪里放置 const 和条件渲染在代码中并使其工作。大家提前。

代码如下:

const Research: FC<ResearchProps> = memo(
  ({ research, hideLabel = false, intl }) => (
    <div className="section research">
       <div className="section__value" id="container-research-value">
        <div className="research-info">
          <div className="description" id="element-research-description">
            <PopoverWrapper
              id="element-research-description-tooltip"
              trigger="hover"
              placement="top"
              speaker={<span className="text-tooltip">{research.data.description}</span>}
            >
              **<span>{`${research.data.codesRelated[1].code} ${research.data.description}`}</span>**
            </PopoverWrapper>
          </div>

【问题讨论】:

  • 可以把它放在那里,虽然我不会——最好在渲染之前拉出字符串。

标签: javascript reactjs typescript jsx


【解决方案1】:

你可以试试这个

const Research: FC<ResearchProps> = memo(
  ({ research, hideLabel = false, intl }) => (
    <div className="section research">
       <div className="section__value" id="container-research-value">
        <div className="research-info">
          <div className="description" id="element-research-description">
            <PopoverWrapper
              id="element-research-description-tooltip"
              trigger="hover"
              placement="top"
              speaker={<span className="text-tooltip">{research.data.description}</span>}
            >
              <span>{research.data.codesRelated[1].code === undefined ?
                        research.data.description
                      : <>
                       {research.data.codesRelated[1].code} {research.data.description}
                      </>}
              </span>
            </PopoverWrapper>
          </div>

【讨论】:

  • 你的代码 sn-p 运行失败,Uncaught SyntaxError: Missing initializer in const declaration
【解决方案2】:

如前所述,您可以使用三元运算符。

您可以使用一个简单的技巧:对字符串模板末尾有空格的代码进行条件渲染。

<span>
{research.data.codesRelated[1].code && `${research.data.codesRelated[1].code} `}
{`${research.data.description}`}
</span>

但最好的方法是创建一个外部函数来构建这个字符串。你的渲染会是这样的:

<span>
{buildResearchDescription(research.data)}
</span>

【讨论】:

  • 感谢您的回答,但似乎没有验证 research.data.codesRelated[1].code === undefined
  • const research = { data: { description: "Some description", codesRelated: [{}, {}] }, } 有了这个数据结构,它就可以正常工作了。 jsx 中的花括号内只是 javascript 代码。
猜你喜欢
  • 2021-08-09
  • 2013-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
相关资源
最近更新 更多