Skip to content

Instantly share code, notes, and snippets.

@YouMinTW
Last active June 20, 2021 04:25
Show Gist options
  • Save YouMinTW/4902b7dc197420dd6999a0b45e8357b5 to your computer and use it in GitHub Desktop.
Save YouMinTW/4902b7dc197420dd6999a0b45e8357b5 to your computer and use it in GitHub Desktop.
  1. Parent, ChildA, ChildB
const Parent = ()=>{
  return (
    <div>
      <ChildA />
      <ChildB />
    </div>
  )
}
  1. ChildA, ChildB 的狀態跟資料處理方式相當接近,只是元件樣式或行為不太一樣
  2. 能不能不要一直重複寫相同的狀態管理?
  3. 能不能讓 <Parent> 決定 <Child> 的元件、樣式要長什麼樣子,<Child> 專注在資料、狀態管理。
const Child = (元件產生器) =>{
  const [count,setCount]= useState(0)

  return 元件產生器 帶入 count, setCount

}
const Child = ({render}) => {
  const [count,setCount]= useState(0)
  // render 是一個 function 他吃Child 給的參數,回傳一組元件
return <div>
        { render(count, setCount) }
       </div>
}

所以就可以讓外面的人決定要渲染什麼元件

const Parent = ()=>{
return (
  <div>
    <Child />
    <Child render={(count,setCount)=><button onClick={()=>setCount(count+1)}>Count is {count} </button>} />
  </div>
)
}
  1. 其他共用邏輯的方法:custom hook
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment