一 基础

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) }
}

最新文章

  1. 基于OWIN WebAPI 使用OAUTH2授权服务【授权码模式(Authorization Code)】
  2. Memory Allocation API In Linux Kernel &amp;&amp; Linux Userspace、kmalloc vmalloc Difference、Kernel Large Section Memory Allocation
  3. 利用cocostudio库函数 实现左右滑动的背包栏UI (cocos2d-x 2.2.0)
  4. poj 2942 点的双连通分量
  5. Qt 学习之路 2(79):QML 组件
  6. [转] nginx 开启gzip压缩--字符串压缩比率很牛叉
  7. spring mvc 提交表单的例子
  8. jquery刷新iframe页面的方法(兼容主流)
  9. 第八篇 一个用JS写的省市县三级联动
  10. 详解Mysql自动备份与恢复
  11. python基础(1)
  12. Redis两种秒杀抢购思路
  13. codeforces #530 D(Sum in the tree) (树上贪心)
  14. Vue中splice的使用
  15. HTTP 协议基础概念和报文结构
  16. mybatis学习系列五--插件及类型处理器
  17. 洛谷 P4475 巧克力王国 解题报告
  18. RxJS之转化操作符 ( Angular环境 )
  19. Hibernate+struct web项目问题总结
  20. BugPhobia开发篇章:Beta阶段第V次Scrum Meeting

热门文章

  1. 判断条件为NULL
  2. .NET周报【12月第4期 2022-12-31】
  3. S2-012 CVE-2013-1965
  4. Vue 快速入门(一)
  5. 前端必备基础知识之--------原生JS发送Ajax请求
  6. Docker快速部署Nacos
  7. 记OPNsense防火墙的安装过程 - 安全
  8. 练习:集合元素处理(传统方式)-练习:集合元素处理(Stream方式)
  9. Unity - 无限滚动
  10. 走进Linux