目录
- 组件嵌套
- 组件通信
组件嵌套
- 写好子组件Test.jsx(src/components/Test.jsx)
import React from "react";
export default class Test extends React.Component {
render(){
return (
<div>
子组件1
</div>
)
}
}
- 在父组件(src/App.js)中进行引入
import React from "react";
import Test from "./components/Test"
export default class App extends React.Component{
render(){
return (
<div>
Hello World!
<Test />
</div>
)
}
}
-
运行效果:
运行效果
组件通信
父传子
- 在父组件定义好传入数据
import React from "react";
import Test from "./components/Test"
export default class App extends React.Component{
constructor(){
super()
this.state = {
msg:'来自父组件的消息--直接传入', // 直接写入子组件
anotherMsg:'', //通过事件的方式,通知子组件
}
}
transToSon = ()=>{
this.setState({
anotherMsg:'来自父组件的消息'
})
}
render(){
let {msg,anotherMsg} = this.state;
return (
<div>
Hello World!
<Test msg={msg} anotherMsg={anotherMsg}/>
<button onClick={this.transToSon}>点击向子组件传入消息</button>
</div>
)
}
}
- 子组件进行接收,并显示
import React from "react"
export default class Test extends React.Component {
render () {
let {msg,anotherMsg} = this.props;
return (
<div>子组件--{msg}---{anotherMsg}</div>
)
}
}
-
查看页面效果
页面效果
子传父
- 在父组件定义好接收子组件的事件,并绑定在子组件上
import React from "react";
import Test from "./components/Test"
export default class App extends React.Component{
constructor(){
super()
this.state = {
msg:'来自父组件的消息--直接传入', // 直接写入子组件
anotherMsg:'', //通过事件的方式,通知子组件
}
}
//通知子组件
transToSon = ()=>{
this.setState({
anotherMsg:'来自父组件的消息'
})
}
//来自子组件的消息通知
_comeFromSon = (val)=>{
this.setState({
msg:val
})
}
render(){
let {msg,anotherMsg} = this.state;
return (
<div>
Hello World!
<Test msg={msg} anotherMsg={anotherMsg} _comeFromSon={this._comeFromSon}/>
<button onClick={this.transToSon}>点击向子组件传入消息</button>
</div>
)
}
}
- 在子组件定义好向父组件通信的事件,通过调用父组件定义的接收方法,来进行通知。
import React from "react"
export default class Test extends React.Component {
//通知父组件改消息
transToParent = ()=>{
this.props._comeFromSon('我是子组件,我想改消息')
}
render () {
let {msg,anotherMsg} = this.props;
return (
<div>
子组件--{msg}---{anotherMsg}
<button onClick={this.transToParent}>向父组件传入数据</button>
</div>
)
}
}

