iT邦幫忙

2021 iThome 鐵人賽

DAY 2
0
自我挑戰組

React 學習之路系列 第 2

什麼是 JSX (Day2)

介紹JSX

JSX 是一種在 JavaScript 裡面的標籤語法,讓我們可以在寫邏輯時使用 HTML 標籤。
React 基本概念是:「建立元件,而不是樣板」。

話說在設計軟體時都會考量關注點分離,從 MVC 的架構開始,單純的把邏輯 (Model) 跟樣板 (View) 分開,
到發現只是技術上的區分,也把處理需求時,邏輯與樣板兩部份,相互需要對應注意的部分分開了。在影片 React:重新思考 best practices 提到一句話,「templates separate technologies, not concern」。

注:React:重新思考 best practices 裡面有講到完整的思考脈絡,從建立元件的先決條件、React 設計決策、到實作方法,推薦觀看。

JSX 裡的 {} 、() 、與注意最外層只能有單一元素

以下舉例 JSX 一些用法:

{ } 可以放置變數(文字或屬性都可)、或 JS Expression ,並回傳顯結果,

const faith = <h1>I believe {1 + 1} > 2</h1>;

function person(name) {
  if (name) {
    return <h1>Hello, { name }!</h1>;
  }
  return <h1>Hello, Stranger.</h1>;
}

const user = {
  John: 'www.handsome.com/profile.jpg',
  Merry:'www.beautiful.com/profile.jpg'
}

const element = <img src={user.John}></img>;

( ) 當包多元素的時候必須使用

const fruits = (
<ul>
    <li>?</li>
    <li>?</li>
    <li>?</li>
</ul>);

最外層只能有單一元素

//錯誤的例子
const twins = (
  <h1>我是雙胞胎哥</h1>
  <h1>我是雙胞胎弟</h1> );

JSX 其實要透過 babel 解析

JSX 無法直接寫在我們的 Script 當中,是需要經過 Babel 翻譯成瀏覽器可以看懂的唷!
回頭看 Day1 Hello, 2021 iThome 鐵人賽! 例子,其實會被解析成以下例子。(可使用Bable 工具寫 JSX 看看。)

ReactDOM.render(
  React.createElement("h1", null, "Hello Bable"),
  document.getElementById('root')
);

以上今天。

參考資料:
https://zh-hant.reactjs.org/docs/introducing-jsx.html
React:重新思考 best practices
Microsoft 架構原則


上一篇
30 天 React 學習之路 (Day1)
下一篇
Render Element(Day3)
系列文
React 學習之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言