【问题标题】:Ternary Operator in JSX - Alternative?JSX 中的三元运算符 - 替代方案?
【发布时间】:2020-09-25 20:39:46
【问题描述】:

我发现自己最近在 React 中做了很多 if-else 条件,但实际上并不需要 else 上的任何东西:

{node.tags ?
  <div className="tags"> {
    node.tags.map(e =>
      <p key={e}>{e}</p>
    )}
  </div> :
  <></>
}

有没有更简洁的方法,还是标准?

我正在考虑在函数中执行此操作 - 但我不确定有哪些替代方法:

const getTags = (node) => {

  if (!node.tags) {
    return;
  }

  return (
    <div className="tags"> {
      node.tags.map(e =>
        <p key={e}>{e}</p>
      )}
    </div>
  )
}

【问题讨论】:

  • "{node.tags && }"
  • 如有疑问,请查看文档React Conditional Rendering
  • 我建议在三元中返回 null 而不是 > 以避免无用的渲染。

标签: javascript reactjs jsx


【解决方案1】:

在大多数情况下,您可以将其简化为:

{node.tags &&
  <div className="tags"> {
    node.tags.map(e =>
      <p key={e}>{e}</p>
    )}
  </div>
}

【讨论】:

  • 啊,好吧。我已经看过几次了,但从来没有真正想过它是什么。那叫什么?
  • 称为“条件渲染”。
  • @Oyyou 叫做“逻辑与”。就是说:如果你经常这样做,你可能会错过一些重构。
【解决方案2】:

我喜欢将&amp;&amp; 用于此目的,如下所示:

{
  node.tags &&
  <div className="tags">
     {
         node.tags.map(e => <p key={e}>{e}</p>)
     }
  </div>  
}

您可以在Conditional Rendering 文档中阅读有关&amp;&amp; 的更多信息。尤其是 Inline If with Logical && Operator 部分,其中指出:

您可以通过将表达式包裹在花括号中来将表达式嵌入 JSX。这包括 JavaScript 逻辑 &amp;&amp; 运算符。它可以很方便地有条件地包含一个元素。

【讨论】:

    【解决方案3】:

    我通常为所有条件创建一个ShowHide 组件,为Arrays 创建一个map-function

    const ShowHide = ({show, children}) => show && children
    
    const Tag = ({tag}) => <p>{tag}</p>
    
    const mapTagsToJSX = tags => tags && tags.map(tag => (<Tag key={tag} tag={tag} />))
    
    const Tags = ({tags}) => (
        <div>
          <ShowHide show={tags}>
              {mapTagsToJSX(tags)}
          </ShowHide>
          <ShowHide show={!tags}>
            loading tags...
          </ShowHide>
        </div>
      )
      
    const useTags = () => {
      const [tags, setTags] = React.useState(null)
      React.useEffect(() => {
        setTimeout(() => {
          setTags([1,2,3])
        }, 1000)
      }, [])
      return tags;
    }
    
    const App = () => {
     const tags = useTags()
     return (<Tags tags={tags}/>)
    }
    
    const root = document.getElementById('root');
    
    ReactDOM.render(<App />, root)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
    
    <div id="root"></div>

    祝你好运……

    【讨论】:

      猜你喜欢
      • 2011-12-15
      • 2020-10-06
      • 2023-04-10
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 2018-03-06
      相关资源
      最近更新 更多