React概念:組合
什麼是組合,為什麼它是React應用中的關鍵概念?
在程式設計中,組合允許您通過結合小而專注的函數來構建更複雜的功能。
例如,想象使用map()從初始數組創建新的數組,然後使用filter()過濾結果:
1 2
| const list = ['Apple', 'Orange', 'Egg'] list.map(item => item[0]).filter(item => item === 'A')
|
在React中,組合使您能夠享受一些很棒的優勢。
您可以創建小而精簡的組件,並使用它們來組合更多的功能。該怎麼做呢?
創建組件的專用版本
使用外部組件來擴展和專門化一個更通用的組件:
1 2 3 4 5 6 7 8 9 10 11
| const Button = props => { return <button>{props.text}</button> }
const SubmitButton = () => { return <Button text="Submit" /> }
const LoginButton = () => { return <Button text="Login" /> }
|
將方法作為props傳遞
組件可以專注於跟蹤點擊事件,例如,當點擊事件發生時,實際發生的事情由容器組件決定:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const Button = props => { return <button onClick={props.onClickHandler}>{props.text}</button> }
const LoginButton = props => { return <Button text="Login" onClickHandler={props.onClickHandler} /> }
const Container = () => { const onClickHandler = () => { alert('clicked') }
return <LoginButton onClickHandler={onClickHandler} /> }
|
使用children
props.children屬性允許您在其他組件中注入組件。
組件需要在其JSX中輸出props.children:
1 2 3
| const Sidebar = props => { return <aside>{props.children}</aside> }
|
您可以以透明的方式將更多組件嵌入其中:
1 2 3 4
| <Sidebar> <Link title="First link" /> <Link title="Second link" /> </Sidebar>
|
高階組件
當一個組件接收一個組件作為prop並返回一個組件時,它被稱為高階組件。
您可以在我的文章React高階組件中了解更多高階組件的內容。
tags: [“React”, “composition”, “components”, “higher order components”]