2025年4月22日 星期二

React class & style(3)

1.先清除index.css,換成
.parent{
    color:  rgb(147, 60, 229);
}

.child{
    color: rgb(232, 150, 27);
    background-color: rgb(234, 78, 11);
}

2.接著回到App.jsx加入class
const Child = () => {
  return (
    <>
      <h3 className="child">Child Component</h3>
    </>
  )
}

const App = () => {
  return (
    <>
      <h2 className="parent">App Component</h2>
      <Child />
      <Child />
    </>
  )
}
export default App
React的class必須寫成className
3.修改Child component加入inline styles
const Child = () => {
  return (
    <>
      <h3 className="child" style={{
        backgroundColor: '#BBFFFF'
      }}>Child Component</h3>
    </>
  )
}
原css中如有-則使用小駝峰(lower camel case)
inline styles優先度大於class
參考資料
Adding styles
React JS 19 Full Course 2025 | Build an App and Master React in 2 Hours

React Component(2)

React Component寫法有蠻多種的
以下是個人覺得比較簡潔的
1.將App.jsx內容先全部清除改成
const App = () => {
  return (   
      <h2>App Component</h2>   
  )
}
export default App
完成第一個Component了
2.接著新增一個Child Component
const Child = () => {
  return (
    <>
      <h3>Child Component</h3>
    </>
  )
}
3.在App Component中使用多個Child Component
const App = () => {
  return (
    <>
      <h2>App Component</h2>
      <Child />
      <Child />
    </>
  )
}
export default App
表示Component可重複使用
特別注意 Component第一個字為大寫
參考資料
Your First Component
React JS 19 Full Course 2025 | Build an App and Master React in 2 Hours