1. 父组件向子组件通信
通过props
父组件内容
import React, { Component } from 'react'
import Child from './component/Child/index'
export default class app extends Component {
state = {
msg: '我是父组件'
}
render() {
const { msg } = this.state
return (
<div>
<Child msg={msg}/>
</div>
)
}
}
子组件的内容
import React, { Component } from 'react'
export default class Child extends Component {
render() {
const { msg } = this.props
return (
<div>
<h2>{ msg }</h2>
</div>
)
}
}
2.子组件向父组件通信
通过props和触发回调函数
父组件内容
import React, { Component } from 'react'
import Child from './component/Child/index'
export default class app extends Component {
state = {
msg: ''
}
onHandel = (val) => {
const { msg } = this.state
this.setState({msg: msg})
}
render() {
const {msg} = this.state
return (
<div>
<Child onHandel={this.onHandel} />
<h2>{msg}</h2>
</div>
)
}
}
子组件的内容
import React, { Component } from 'react'
export default class Child extends Component {
onHandelChid = () => {
this.props.onHandel('我是子组件传过来的值')
}
render() {
return (
<div>
<button onClick={this.onHandelChid}></button>
</div>
)
}
}
本文详细介绍了在React中如何进行父子组件间的通信。首先,展示了如何通过props将父组件的状态传递给子组件。接着,通过设置回调函数,演示了子组件如何修改父组件的状态,从而实现双向通信。实例代码清晰地解释了这一过程。
266

被折叠的 条评论
为什么被折叠?



