【React】组件通信 - 父传子
组件通信
概念
- 组件通信就是组件之间的数据传递,根据组件嵌套关系的不同,有不同的通信方法。
分类
- 父子通信、兄弟通信、跨层通信
父传子
实现步骤
- 父组件传递数据 - 在子组件标签上绑定属性
- 子组件接收数据 - 子组件通过props参数接收数据
示例
-
function Son(props) { return <div>this is son, {props.name}</div> } function App() { const name = 'this is farther' return ( <div> <Son name={name} /> </div> ); } ...
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>
);
}
...
本文作者:505donkey
本文链接:https://www.cnblogs.com/505donkey/p/18391183
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步