父子传值
父传子
将子组件导入父组件并使用,在注册的子组件标签上通过自定义属性接收要传递的变量或者方法,在父组件的constructor(props)可以通过props属性接收父组件传递过来的方法
// 子组件
import {Component} from 'react'
class Child extends Component {
// 在子类中如果要使用constructor函数就必须写super关键字
constructor(props) {
super()
// props里面会包含父组件传递过来的值 接收的是自定义属性和值的键值对
console.log(props.text) // 呼哈有
}
}
// 父组件
import {Component} from 'react'
import Child from '子组件的文件地址'
class Parent extends Component {
// 定义一个react组件 render函数时必须的
render() {
return (
// react组件的根元素不能有同胞元素
// 组件的首字母必须大写
<div>
<Child text="呼哈有"/>
</div>
)
}
}
子传父
通过父组件的自定义属性将父组件的方法或者函数传递给子组件,然后在子组件中调用该方法
需要注意的是:特别注意this指向
//父组件
import {Component} from 'react'
import Child from '子组件所在的文件地址'
class Parent extends Component {
getData = (val) => {
console.log(val) // 就是子组件传递过来的值
}
render() {
return (
<div>
<Child func={this.getData}/>
</div>
)
}
}
import {Component} from 'react'
class Child extends Component {
// 在子类中如果要使用constructor函数就必须写super关键字
constructor(props) {
super()
// props里面会包含父组件传递过来的值 接收的是自定义属性和值的键值对
}
setData(val) {
this.props.func(val)
}
render() {
return (
<div>
<button onClick={this.setData.bind(this, "我要传递的数据")}>点击</button>
//也可以这样写
<button onClick={() => this.props.func("我要传递的数据")}>点击</button>
</div>
)
}
}