父传子
Parent
import React, { Component } from 'react'
import Child from './child'
export default class Parent extends Component {
constructor(){
super()
this.state={
name:"Parent"
}
}
render() {
return (
<div>
111
<Child name = {this.state.name}></Child>
//Parent如果还有父元素,则可以给子元素传递{...this.[}
</div>
)
}
}
child
import React, { Component } from 'react'
export default class Child extends Component {
constructor(){
super()
}
render() {
console.log(this.props)//{name: "Parent"}
return (
<div>
2222
</div>
)
}
}
子传父
父组件
import React, { Component } from 'react'
import Child from './child'
export default class Parent extends Component {
constructor(){
super()
this.state={
name:"Parent"
}
}
fn(){
console.log('我是从子组件传来的')//我是从子组件传来的
}
render() {
return (
<div>
<Child tochild = {this.fn}></Child>
</div>
)
}
}
子组件
import React, { Component } from 'react'
export default class Child extends Component {
constructor(){
super()
}
render() {
this.props.tochild()
return (
<div>
2222
</div>
)
}
}
子组件this.props可以调用注册store,路由信息等。