React(7) --react父子组件传参
2024-08-27 19:35:30
react父子组件传参
父级向子级传参:在父组件中,我们引入子组件,通过给子组件添加属性,来起到传参的作用,子组件可以通过props获取父组件传过来的参数。
在父组件中:
import React from 'react'
import ChildCom from './childCom.js'
class ParentCom extends React.Component {
render() {
return (
<div>
<h1>父组件</h1>
<ChildCom content={'我是父级过来的内容'}/>
</div>
)
}
}
export default ParentCom;
在子组件中:
import React from 'react'
class ChildCom extends React.Component {
render() {
return (
<div>
<h2>子组件</h2>
<div>
{this.props.content}
</div>
</div>
)
}
}
export default ChildCom;
子级向父级传参:在父组件中给子组件添加一个属性,这个属性的内容为一个函数,然后在子组件中调用这个函数,即可达到传递参数的效果
在子组件中:
import React from 'react'
class ChildCom extends React.Component {
valueToParent(value) {
this.props.onValue(value);
}
render() {
return (
<div>
<h2>子组件</h2>
<div>
<a onClick={this.valueToParent.bind(this,)}>向父组件传值567</a>
</div>
</div>
)
}
}
export default ChildCom;
在父组件中:
import React from 'react'
import ChildCom from './childCom.js'
class ParentCom extends React.Component {
state = {
getChildValue: ''
}
getChildValue(value) {
this.setState({
getChildValue: value
})
}
render() {
return (
<div>
<h1>父组件</h1>
<div>子组件过来的值为:{this.state.getChildValue}</div>
<ChildCom onValue={this.getChildValue.bind(this)}/>
</div>
)
}
}
export default ParentCom;
最新文章
- js面向对象
- iOS RESideMenu 侧滑 第三方类库
- 关于Xcode8.1 / iOS10+ 真机测试系统打印或者宏定义打印不显示问题
- 基本I/O模型与Epoll简介
- JVM知识点
- Android EditText 文本框实现搜索和清空效果
- Python3基础 多分支结构 if-elif-else
- storm集成kafka
- 能够兼容ViewPager的ScrollView
- SPI协议总结
- 从Object和Function说说JS的原型链
- Kafka 安装配置 windows 下
- vue-cli环境配置
- http-cookie、session、Token
- PAT 1026 程序运行时间
- android 组件使用()
- 2018 ACM 网络选拔赛 北京赛区
- WordConuts
- 质控工具之TrimGalore使用方法
- IDEA Maven项目 编译的问题