文章目录
父子组件的传值
在react中,父传子可以使用props的方法,子传父使用props的回调函数
父组件:
在父组件中定义state,将这个state对象传给子组件,所以可以直接在son组件上写{…this.state}
import React, {
Component } from 'react'
import Son from './son'
export class Parent extends Component {
constructor() {
super()
this.state = {
name: '父组件',
msg: '这是父组件的信息'
}
}
render() {
return (
<div>
<h1>Parent Page</h1>
<h2>我是父组件的:{
msg}--{
name}</h2>
<Son {
...this.state} parentChange={
this.parentChange.bind(this)}/>
</div>
)
}
}
export default Parent
子组件:
在state中写入parentMsg: props.msg,这样在页面中可以直接展示parentMsg,也就是父组件传过来的值
import React, {
Component } from 'react'
export class Son extends Component {
constructor(props) {
super()
this.s