【问题标题】:reactjs semantic-ui how to correctly modify a JSX tag conditionallyreactjs语义-ui如何有条件地正确修改JSX标签
【发布时间】:2018-09-30 06:13:17
【问题描述】:

我有一个我想有条件地定义的标签

<Table.Cell positive>{item}</Table.Cell>

那么,正确的做法是什么? 我所做的是用函数代替它

{this.callme(item)}

然后函数返回这个

callme = (item) => {
  let res;
  if (item && item > 3)
    res = <Table.Cell positive>{item}</Table.Cell>
  else if (item && item < -3)
    res = <Table.Cell negative>{item}</Table.Cell>
  else if (item)
    res = <Table.Cell>{item}</Table.Cell>
  else
    res = <Table.Cell>..</Table.Cell>
  return res;

但这很冗长。然后我尝试修改标签 inside 的东西,但这是不允许的

<Table.Cell {mystate}>{item}</Table.Cell>

然后是问题。如何修改标签本身?应该怎么写?

【问题讨论】:

    标签: reactjs semantic-ui semantic-ui-react


    【解决方案1】:

    我建议您对直接返回组件的方法稍作调整,而不是通过res 分配和返回:

    callme = (item) => {
    
      if (item && item > 3)
        return (<Table.Cell positive>{item}</Table.Cell>)
      else if (item && item < -3)
        return (<Table.Cell negative>{item}</Table.Cell>)
      else if (item)
        return (<Table.Cell>{item}</Table.Cell>)
      else
        return (<Table.Cell>..</Table.Cell>)
    }
    

    除此之外,您的一般方法很好,因为它既可读又功能正确。

    或者,您可以像这样修改方法的整体结构以最小化总行数,并将四个返回语句减少到一个返回语句:

    callme = (item) => {
        return (item ? 
        <Table.Cell negative={ item < -3 } positive={ item > 3 }>{item}</Table.Cell> : 
        <Table.Cell>..</Table.Cell>)
    }
    

    【讨论】:

    • 是的,诀窍在于 JSX 中的任何属性确实是我在语义 ui api 中找到的“property=bool”。你的代码正是我想要弄清楚的。非常感谢!
    • 太好了,很高兴我能帮上忙!
    【解决方案2】:

    您可以像这样优化callme 方法:

    callme(item) {
      if(item) {
        return <Table.Cell positive={item > 3} negative={item < -3}>{item}</Table.Cell>
      } else {
        return <Table.Cell>..</Table.Cell>
      }
    }
    

    【讨论】:

    • 虽然正确投票的答案确实有效,但它比它需要的要冗长得多。这个答案要简洁得多。
    猜你喜欢
    • 2021-07-14
    • 2023-02-09
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    相关资源
    最近更新 更多