[30DaysChallenge] React 的小雜事 - fragment

30DaysChallenge 是自主性每兩天寫一篇技術相關的部落格

React

Components

關於包裝元件的小事情之一,都知道只能存在一個 root element

//Button 元件
const Button = () => {
  return (
    <div>
      <button>CLICK!</button>
    </div>
  )
}

//某個不合法的元件
const Button = () => {
  return (
    <button>CLICK!</button>
    <button>CLICK!</button>
  )
}

//可以改這樣包裝
const Button = () => {
  return (
    <div>
      <button>CLICK!</button>
      <button>CLICK!</button>
    </div>
  )
}

最後一種的包裝會有缺點,<div>是實際上存在的元素

既然存在了,就會影響整個畫面

我們可以用幾種方式來包裝


自己刻一個元件

const Wrapper = props => {
  return props.children
}

const Button = () => {
  return (
    <Wrapper>
      <button>CLICK!</button>
      <button>CLICK!</button>
    </Wrapper>
  )
}

React.Fragment

但自己刻一個太麻煩了

使用 React 的 Fragment 也可以

import { Fragment } from "react"

const Button = () => {
  return (
    <Fragment>
      <button>CLICK!</button>
      <button>CLICK!</button>
    </Fragment>
  )
}

或者再偷懶一點,簡化成這樣

不過當簡化這樣時,就不能套入屬性、Key 等等設定

const Button = () => {
  return (
    <>
      <button>CLICK!</button>
      <button>CLICK!</button>
    </>
  )
}

08/27 React 的小雜事 2