Reactjs语义UI如何有条件地正确修改JSX标签

标签 reactjs semantic-ui semantic-ui-react

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

<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;

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

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

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

最佳答案

我建议对您的方法稍作调整,直接返回组件,而不是通过 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>)
}

关于Reactjs语义UI如何有条件地正确修改JSX标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52575157/

相关文章:

javascript - React-router (0.13) + Flux - 如何将 flux 类实例放入 willTransitionTo Hook 中?

javascript - 在 React 中创建更多元素

reactjs - 在 Enzyme 中测试 input.focus()

javascript - 如何将我的项目 'expo' 更改为 ' normal'

html - 语义 UI CSS 右填充

css - 语义ui Accordion 进入模态

javascript - 语义 UI 侧边栏不会显示 - React

dropdown - 如何在其父组件挂载时拥有语义 UI React Dropdown 自动对焦?

javascript - 语义 UI React 项目图像作为链接