React Hooks 學習筆記
阿新 • • 發佈:2020-08-07
1.userContext的使用
使用場景, 元件之間需要共享狀態
父元件
import React, { useState } from 'react';
import Child from './child.js'
import Child2 from './child2.js'
import CountContext from './common'
function Example(){
const [count , setCount ] = useState(666)
return(
<div>
<div>
<p>you click {count -666 } times</p>
<button onClick={()=>{setCount(count+1)}}>click me</button>
<CountContext.Provider value ={count}>
<Child/>
<Child2/>
</CountContext.Provider>
</div>
</div>
)
}
export default Example
子元件1
import React, { useContext } from 'react';
import CountContext from './common'
function Child(){
let count = useContext(CountContext)
return(<h2>兒子1:{count}</h2>)
}
export default Child
子元件2
import React, { useContext } from 'react';
import CountContext from './common'
function Child(){
let count = useContext(CountContext)
return(<h2>兒子2:{count}</h2>)
}
export default Child
公共元件
import {createContext } from 'react';
const CountContext = createContext(80);
export default CountContext
效果
二、父子傳值
父元件
<ConfirmModal
attribution={attribution}
location={props.location}
func={confirmClose}
onFinish={() => {
confirmClose();
setFinish(true);
}}
agent_id={
props.location.query.agent_id
? props.location.query.agent_id
: ''
}
values={values}
number={number}
products={screen.products}
/>
子元件
export default ({location, values, products, number = { price: 0 }, func, onFinish, attribution, agent_id}) => {
//觸發父元件函式
onFinish && onFinish(); //可傳值
}