组件通信
概念
- 组件通信就是组件之间的数据传递,根据组件嵌套关系的不同,有不同的通信方法。
分类
父传子
实现步骤
- 父组件传递数据 - 在子组件标签上绑定属性
- 子组件接收数据 - 子组件通过props参数接收数据
示例
props参数
说明
- props可以传递任意的数据:数字、布尔值、字符串、数组、对象、函数、JSX。
- props是只读对象:子组件只能读取props中的数据,不能直接进行修改,父组件的数据只能由父组件修改。
示例
function Son(props) {
return <div>this is son, {props.name}</div>
}
function App() {
const name = 'this is farther'
return (
<div>
<Son
name={name}
age={18}
isTrue={false}
list={['vue','react']}
obj={{ name: 'dkyzheng'}}
cb={()=>{console.log('this is cb')}}
/>
</div>
);
}
...
children
场景
- 当我们把内容嵌套在子组件标签时,父组件会自动在名为children的prop属性中接收该内容
示例
function Son(props) {
return <div>this is son, {props.children}</div>
}
function App() {
const name = 'this is farther'
return (
<div>
<Son>
<span>this is span</span>
</Son>
</div>
);
}
...