【问题标题】:if statement not returning as an object React JSif 语句不作为对象返回 React JS
【发布时间】:2021-04-14 04:36:05
【问题描述】:

我正在尝试在样式标签中编写两个表达式,但它一直给我以下错误The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.我该如何解决?

<table id='calendario'>
              <tbody>
                {linhas.map((linha) => (
                  <tr key={linha}>
                  {colunas.map((coluna , e , i) => (
                  <td
                  key={coluna} onLoad={() => {
                    if(e < index.length){e = e};
                    if(i >= proximo_mes.length){i = i};
                  }}
                  style={() => {if(linha == 0 && coluna == e){return {filter : 'brightness(0.6)'}};
                  if(linha == 4 && coluna == i){return{filter : 'brightness(0.6)'}}
                  else{return{filter : 'brightness(1)'}}}}
                ></td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>

【问题讨论】:

    标签: javascript css reactjs frontend react-dom


    【解决方案1】:

    像这样使用ternary operator

    style={(linha == 0 && coluna == e) ? {filter : 'brightness(0.6)'} : (linha == 4 && coluna == i) ? {filter : 'brightness(0.6)'} :  {filter : 'brightness(1)'}}
    

    或者这个:

    style={{filter :(linha == 0 && coluna == e) ? 'brightness(0.6)' : (linha == 4 && coluna == i) ?'brightness(0.6)' : 'brightness(1)'}}
    

    发生错误是因为您返回的是function 而不是object,请查看以下示例:

    console.log("Function Style: ", {
      style: () => {
        if (true) {
          return { filter: "brightness(0.6)" };
        }
      }
    })
    
    console.log("Ternary Style: ", {
      style: true ? { filter: "brightness(0.6)" } : { filter: "brightness(1)" }
    })

    【讨论】:

    • 非常感谢,但你能告诉我为什么我的没用吗?
    • 没问题,再次检查答案我为这种情况做一个例子。
    猜你喜欢
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2018-05-07
    相关资源
    最近更新 更多