// 父传子组件
import React from 'react';
import ReactDOM from 'react-dom';
class Father extends React.Component{
state = {
message:"刘德华bb",
}
render() {
return(
<div>
父组件|调用子组件:<Child msg={this.state.message}/>
</div>
)
}
}
// function Child(props){
// return <div>{props.name}</div>
// }
const Child = (props)=>{
return <div>子组件内容 {props.msg} </div>
}
ReactDOM.render(<Father/>,document.getElementById("root"))
//子传父 利用回调函数 父组件提供回调函数 将要传递的数据作为回调函数参数 //1.父组件提供一个函数 接收参数 //2.将该函数作为属性的值 传递给子组件 //3.子组件通过props调用回调函数 //4.将子组件的数据作为参数传递给回调函数
import React from 'react';
import ReactDOM from 'react-dom';
class Father extends React.Component{
state ={
m:"",
}
getChildMsg = (msg)=>{
console.log("接收来自子组件的东西",msg)
this.setState({
m:msg,
})
}
render() {
return(
<div>
<Child get={this.getChildMsg} />
{this.state.m}
</div>
)
}
}
class Child extends React.Component {
state ={
msg:"子组件数据斗鱼",
}
handleClick = ()=> {
// this.state.msg作为回调函数的参数 传到父组件
this.props.get(this.state.msg)
}
render() {
return (
<button onClick={this.handleClick}> 点击:给父组件传东西</button>
)
}
}
ReactDOM.render(<Father/>,document.getElementById("root"))
// ——————————————————————兄弟组件通讯
import React from "react";
import ReactDOM from 'react-dom';
class Father extends React.Component{
state = {
number:1,
}
handClick = ()=>{
this.setState({
number:this.state.number+1,
})
}
render(){
return(
<div>点击次数:
<Child1 number={this.state.number}/>
<Child2 handClick={this.handClick}/>
</div>
)
}
}
const Child1 = (props) =>{
return <div>{props.number}</div>
}
const Child2 = (props) =>{
return <button onClick={()=>{props.handClick()}}>点击</button>
}
ReactDOM.render(<Father/>,document.getElementById("root"))
|