1.子传父 通过props传递 props是只读对象不可修改,如果修改只能通过父组件
function App(){
const name = 'this is name'
return (
<div>
<Son name={name}/>
</div>
)
}
function Son(props){
return(
<div>
<span>
{props.name}
</span>
</div>
)
}
1.1 特殊的props children,吧内容嵌套在子组件里,父组件会自动在名为children的props属性接收
function Son(props){
return(
<div>
{props.children} // 这里就会显示父组件传递的span
</div>
)
}
function App(){
return (
<div>
<Son>
<span>this is span</span>
</Son>
</div>
)
}
2.子传父 在组件里调用父组件方法并传递参数
function Son({onGetMessage}){
const msg = "this is msg“
return(
<div>
<button onClick={() => onGetMessage(msg)}></button>
</div>
)
}
function App(){
const getMessage = (msg) => {
console.log(msg)
}
return (
<div>
<Son onGetMessage={getMessage}/>
</div>
)
}
3.兄弟组件通信 先通过子组件传递父组件 在通过父组件传递子组件
function App() {
const [name, setName ] = useState("")
const getMessage = (msg) => {
setName(msg)
}
return(
<div>
<A onGetMessage={getMessage}/>
<B name={name}/>
</div>
)
}
function A({ onGetMessage}) {
const msg = " this is msg"
return(
<div>
<button onClick={() => onGetMessage(msg) }></button>
</div>
)
}
function B(props){
return(
<duv>
{props.name}
</div>
)
}
4跨层级组件传递 使用createContext方法创建上下文对象 在顶层组件app通过ctx.provider 组件提供数据,在底层组件 通过useContext钩子函数使用数据
import { createContext, useContext } from 'react'
const ctxContext = createContext()
function App() {
const msg = "this is msg"
retutn(
<ctxContext.provider value={msg}>
<div>
<A />
</div>
</ctxContext.provider>
)
}
function A(){
return(
<div>
<B />
</div>
)
}
function B(){
const msg = useContext(ctxContext)
return(
<div>
{msg}
</div>
)
}