React
🌸 您好,欢迎您的阅读,等君久矣,愿与君畅谈.
🔭 § 始于颜值 § 陷于才华 § 忠于人品 §
📫 希望我们可以进一步交流,共同学习,共同探索未知的技术世界 稀土掘金 OR GitHub.
# 组件通信
-
父子组件通信
-
父组件传递子组件数据通信
-
父组件通过
属性=值的形式来传递给子组件数据 -
子组件通过
props参数获取父组件传递过来的数据 -
类组件之间传参
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32class Children extends Component{
// 构造方法,方式一
// constructor(props){
// super();
// this.props = props;
// }
// 构造方法,方式二
// constructor(props){
// super(props);
// }
// 构造方法,方式三
// 不写,子类的默认构造方法可以省略
render(){
const { name,age,height } = this.props;
return (
<div>
<h2>子组件显示数据:{name+" "+age+" "+height}</h2>
</div>
)
}
}
export default class App extends Component {
render() {
return (
<div>
<Children name="why" age="20" height="188"></Children>
<Children name="GXX" age="22" height="172"></Children>
</div>
)
}
} -
函数组件之间传参
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19function Children(props) {
const { name,age,height } = props;
return (
<div>
<h2>App_函数组件</h2>
<h2>{name+" "+age+" "+height}</h2>
</div>
)
}
export default class App extends Component {
render() {
return (
<div>
<Children name="why" age="20" height="188"></Children>
<Children name="GXX" age="22" height="172"></Children>
</div>
)
}
} -
组件参数类型验证
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41import PropTypes from 'prop-types'
function Children(props) {
const { name,age,height,names} = props;
return (
<div>
<h2>App_函数组件</h2>
<h2>{name+" "+age+" "+height}</h2>
<ul>
{
names.map((item,index)=>{
return <li>{item}</li>
})
}
</ul>
</div>
)
}
// 设置属性类型验证
Children.propsTypes = {
name:PropTypes.string.isRequired,
age:PropTypes.number,
height:PropTypes.number,
names:PropTypes.array
}
// 设置属性默认值
Children.defaultProps = {
name:"XGG",
age:12,//默认类型也会进行类型判断
height:199,
names:["123","456","789"]
}
// 补充:类组件的相关属性编写规范
class Children2 extends Component{
//es6中class fields写法,给类上添加属性,而非对象上
static propsTypes ={
}
static defaultProps ={
}
}
Children2.propsTypes = {
}
-
-
子组件传递父组件通信
- 父组件给子组件传递一个回调函数,在子组件中调用这个函数即可
- 子组件可以通过该回调函数向父组件传递参数
-
模拟插槽样式
-
-
跨组件通信 (数据传递)
- 按照层次依次传递:
Spread Attributes,可以使用属性展开符:...,但是此方案对于中间层会存在冗余操作 - 使用 ReactAPI:
ContextReact.createContext: 创建一个需要共享的对象,若某组件订阅Context时该组件会从距离自身最近的匹配Provider中读取到当前Context值,defaultValue是组件在顶层查找过程中没有找到对应的Provider, 就会使用默认值。context.Provider: 在创建Context对象(context) 时会返回一个Provider React组件,它允许消费组件订阅Context变化,Provider接收一个属性value属性传递给消费组件,一个Provider可以和多个消费组件有对应关系,多个Provider可以嵌套使用,里层会覆盖外层数据;当Provider的value值发生变化时,它内部所有的消费组件都会重新渲染contextType: 挂载在class上的contextType属性会被重新赋值为一个由React.createContext创建的Context对象,这可以使用this.context来获取最近Context上的值;可以在任何生命周期中访问到,包括render函数Consumer: React 组件可以订阅到 context 变化,可以在函数式组件中完成订阅 context,需要函数作为子元素,该函数接收当前的 context 值,返回一个 React 节点
- 按照层次依次传递:
-
events(全局事件传递)npm install events: 安装- 常用 API
eventBus对象:创建 EventEmitter 对象eventBus.emit("事件名称",参数列表): 发出事件eventBus.addListener("事件名称",监听函数): 监听事件eventBus.removeListener("事件名称",监听函数): 移除事件