一、父传子
- 父组件在使用子组件时,提供要传递的数据
- 子组件通过
props
接收数据
class Parent extends React.Component {
render() {
return (
<div>
<div>我是父组件</div>
<Child name="张" age={16} />
</div>
)
}
}
const Child = props => {
return (
<div>
<div>我是子组件</div>
<div>
从父组件接收来的数据: {props.name}-{props.age}
</div>
</div>
)
}
二、子传父
- 父组件在使用子组件时,提供一个
回调函数
,用于接收数据 - 子组件通过
props
调用回调函数,将要传递的数据作为参数传递给回调函数
class Parent extends React.Component {
getChildMsg = (msg) => {
console.log('从子组件接收来的数据:', msg)
}
render() {
return (
<div>
<div>我是父组件</div>
<Child getMsg={this.getChildMsg} />
</div>
)
}
}
const Child = props => {
handleClick = (msg) => {
this.props.getMsg('123abc')
}
return (
<div>
<div>我是子组件</div>
<button onClick={this.handleClick}>
点我,给父组件传递数据
</button>
</div>
)
}
三、无关组件通讯
- 调用
React.createContext()
创建 Provider 和 Consumer 两个组件 - 使用
Provider
组件作为父节点,设置value
属性,表示要传递的数据 - 调用
Consumer
组件接受数据
import React from 'react'
const { Provider, Consumer } = React.createContext()
class Parent extends React.Component {
render() {
return (
<Provider value="red">
<div>
我是Parent
<Child />
</div>
</Provider>
)
}
}
const Child = props => {
return (
<div>
我是Child
<Grandson />
</div>
)
}
const Grandson= props => {
return (
<div>
我是Grandson
<Consumer>{data => 我是Parent接收来的数据: {data}}</Consumer>
</div>
)
}
export default Parent
四、组件间的通讯demo
import React from 'react'
import './index.css'
import PropTypes from 'prop-types'
const { Provider, Consumer } = React.createContext()
class Communication extends React.Component {
render() {
return (
<Provider value="red">
<div className="first">
我是first
<Node name="张" age={16} />
</div>
</Provider>
)
}
}
const Node = props => {
return (
<div className="second">
<div>我是second-Node</div>
<div>
父组件first接收来的数据: {props.name}-{props.age}
</div>
<SubNode
getMsg={msg => {
console.log('second-Node接收到子组件third-SubNode数据:', msg)
}}
/>
</div>
)
}
Node.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
}
Node.defaultProps = {
age: 18,
}
const SubNode = props => {
return (
<div className="third">
<div>我是third-SubNode</div>
<button
onClick={() => {
props.getMsg('三儿')
}}>
点我给父组件second-Node传值
</button>
<Child>我是子节点</Child>
</div>
)
}
const Child = props => {
return (
<div className="fourth">
<div>我是fourth-Child</div>
<Consumer>{data => <span>我是first接收来的数据: {data}</span>}</Consumer>
<div>组件标签的子节点:{props.children}</div>
</div>
)
}
export default Communication