react 03 组件传值
2024-10-20 20:48:48
一 基础
props: 父传子 单向
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'; class ParentCom extends React.Component {
constructor(props) {
super(props)
this.state={
isActive: true
} }
render() {
return (
<div>
<button onClick={()=>{this.show()}}> 控制子组件显示或隐藏(有无子组件,,,也可以通过样式来控制)</button>
<ChildCom isActive={this.state.isActive} />
</div>
)
}
show() {
this.setState({
isActive:!this.state.isActive
})
}
} class ChildCom extends React.Component {
constructor(props) {
super(props)
this.state={}
}
render() {
if(this.props.isActive) {
return (
<div>子组件</div>
)
}else {
return null
} }
} ReactDOM.render(
<div>
<ParentCom />
</div>,
document.getElementById('root')
)
子传 父 单向
将子元素的数据传递给父元素,实际上就是 调用父元素的函数,传参进去
class ParentCom extends React.Component {
constructor(props) {
super(props)
this.state={
msg:null
} }
render() {
return (
<div>
<ChildCom setChildData={this.setChildData} />
{ this.state.msg}
</div>
)
}
setChildData=(childData)=>{
this.setState({
msg:childData
})
}
} class ChildCom extends React.Component {
constructor(props) {
super(props)
this.state={
childData:'我是子组件'
}
}
render() {
return (
<div>
<button onClick={this.sendToParent}>点击传值给父组件</button>
<button onClick={()=>this.props.setChildData(this.state.childData)}>直接调用</button>
</div>
)
}
sendToParent=()=>{
console.log(this.state.childData)
// 将子元素的数据传递给父元素,实际上就是 调用父元素的函数,传参进去
this.props.setChildData(this.state.childData) }
}
最新文章
- 基于OWIN WebAPI 使用OAUTH2授权服务【授权码模式(Authorization Code)】
- Memory Allocation API In Linux Kernel &;&; Linux Userspace、kmalloc vmalloc Difference、Kernel Large Section Memory Allocation
- 利用cocostudio库函数 实现左右滑动的背包栏UI (cocos2d-x 2.2.0)
- poj 2942 点的双连通分量
- Qt 学习之路 2(79):QML 组件
- [转] nginx 开启gzip压缩--字符串压缩比率很牛叉
- spring mvc 提交表单的例子
- jquery刷新iframe页面的方法(兼容主流)
- 第八篇 一个用JS写的省市县三级联动
- 详解Mysql自动备份与恢复
- python基础(1)
- Redis两种秒杀抢购思路
- codeforces #530 D(Sum in the tree) (树上贪心)
- Vue中splice的使用
- HTTP 协议基础概念和报文结构
- mybatis学习系列五--插件及类型处理器
- 洛谷 P4475 巧克力王国 解题报告
- RxJS之转化操作符 ( Angular环境 )
- Hibernate+struct web项目问题总结
- BugPhobia开发篇章:Beta阶段第V次Scrum Meeting