1.父传子
1.1父组件准备数据,父组件通过属性pMsg直接传递给子组件
import React, { Component } from 'react'
import Child from './Child'
export class Parent extends Component {
state = {
msg:'我是父组件的信息' //1.父组件准备数据
}
render() {
return (
<div>
我是父组件
{/* 父组件直接通过属性传递给子组件 */}
<Child pMsg={this.state.msg}></Child>
</div>
)
}
}
export default Parent
1.2子组件通过props接收
import React, { Component } from 'react'
// 子组件
export class Child extends Component {
render() {
// 子组件通过props接收父组件传递的值
console.log(this.props)
return (
<div>
子组件
{/* 使用 */}
<p>{this.props.pMsg}</p>
</div>
)
}
}
export default Child
2.子传父
// 子组件
class Child extends React.Component {
state = {
msg: "短视频",
};
// 子组件调用父组件中传递的回调函数
handClick = () => {
this.props.getMsc(this.state.msg);
};
render() {
return (
<div>
<button onClick={this.handClick}> 点击我 </button>
</div>
);
}
}
// 父组件
class Parent extends React.Component {
state = {
parentMsg: "",
};
// 提供回调函数 接收子组件数据
getChidMsg = (msg) => {
console.log("子组件的数据", msg);
this.setState({
parentMsg: msg,
});
};
render() {
return (
<div>
父组件:{this.state.parentMsg}
<br />
子组件: <Child getMsc={this.getChidMsg}></Child>
</div>
);
}
}
3:非父子组件传值
3.1单独准备一个组件 用来引入另外两个组件
class Parent extends React.Component {
state = {
count: 0,
};
onIncrement = () => {
this.setState({
count: this.state.count + 1,
});
};
render() {
return (
<div>
<Child1 count={this.state.count}></Child1>
<Child2 incrementCount={this.onIncrement}></Child2>
</div>
);
}
}
3.2:组件1
const Child1 = (props) => {
const { count } = props;
return <div> 计数器:{count} </div>;
};
3.3:组件2
const Child2 = (props) => {
const { incrementCount } = props;
function onIncrementCount() {
incrementCount();
}
return <button onClick={onIncrementCount}>+1</button>;
};
4跨组件传值
import React from "react";
import ReactDOM from "react-dom";
// 跨多个组件传值
// 创建context 会得到两个组件
// Provider用来包裹传值组件
// Consumer用来接收传过来的值
const { Provider, Consumer } = React.createContext();
class Parent extends React.Component {
state = {
proData: {
userName: "偶然网",
userPassWord: "123456",
},
};
render() {
console.log(this);
const { proData } = this.state;
console.log("proData", proData);
return (
<Provider value={proData}>
<div
style={{
color: "red",
background: "pink",
height: "600px",
width: "100%",
}}
>
1<Child1></Child1>
</div>
</Provider>
);
}
}
const Child1 = () => {
return (
<div
style={{
color: "red",
background: "green",
height: "400px",
width: "100%",
}}
>
2<Child2></Child2>
</div>
);
};
const Child2 = () => {
return (
<div
style={{
color: "red",
background: "yellow",
height: "200px",
width: "100%",
}}
>
3<Child3></Child3>
</div>
);
};
const Child3 = () => {
return (
<Consumer>
{(data) => (
<div
style={{
color: "red",
background: "purple",
height: "100px",
width: "100%",
}}
>
4 这是接收的数据-------{data.userName} -------{data.userPassWord}
</div>
)}
</Consumer>
);
};
ReactDOM.render(<Parent />, document.getElementById("root"));