父传子
使用props
js
import { useState } from 'react'
function Parent {
const [message, setMessage] = useState('react')
return (
<>
<SonA message={message} />
<SonB message={message} />
</>
)
}
function SonA(props) {
return <div>子组件A: {props.message}</div>
}
function SonB({ message }) {
return <div>子组件B: {message}</div>
}
子传父
子组件调用父组件传递过来的函数,并且把想要传递的数据当成函数的实参传入即可
js
function Parent() {
const getSonMessage = (message) => {
console.log(message)
}
return (
<SonFun
getSonMessage={getSonMessage}
/>
)
}
function SonFun(props) {
const { getSonMessage } = props
const handleClick = () => {
getSonMessage('new message')
}
return (
<button onClick={handleClick}>点击传递数据</button>
)
}
兄弟组件之间的通信
通过状态提升机制,利用共同的父组件实现兄弟组件通信
js
import { useState } from 'react'
function Parent() {
const [message, setMessage] = useState('')
const getSonMessage = (message) => {
setMessage(message)
}
return (
<>
<SonA message={message}></SonA>
<SonB getSonBMessage={getSonMessage} />
</>
)
}
function SonB(props) {
const { getSonBMessage } = props
const handleClick = () => {
getSonBMessage('message from B')
}
return (
<button onClick={handleClick}>点击传递数据</button>
)
}
function SonA(props) {
const { message } = props
return (
<div>{message}</div>
)
}