组件通信
父传子
Parent.js文件里(父组件)
import React from "react";
import { Child } from './Child'
export class Parent extends React.Component {
state = {
Name: 'zy'
}
render() {
return (
<div>
<div>我是父组件,我的名字:{this.state.Name}</div>
<div>我继承了:{this.props.money}块</div>
<Child Name={this.state.Name} />
</div>
)
}
}
Child.js文件了 (子组件)
import React from "react";
export class Child extends React.Component {
render() {
return (
<div>
<hr />
<div>我是子组件,我名字{this.props.Name}</div>
</div>
)
}
子传父
Parent.js文件里(父组件)
import React, { Component } from 'react'
import './Parent.css'
import { Child } from './Child'
export class Parent extends Component {
state = {
money: 100
}
giveMoney = (money) => {
console.log(money);
this.setState({
money: money
})
}
render() {
return (
// 父组件
<div className="parent">
<h1>父组件</h1>
<Child money={this.state.money} giveMoney={this.giveMoney} />
</div>
)
}
}
Child.js文件了 (子组件)
import React, { Component } from 'react'
export class Child extends Component {
render() {
return (
<div className="child">
<h1>{this.props.money}</h1>
<button onClick={() => this.props.giveMoney(300)}>xx</button>
</div>
)
}
}
export default Child
兄弟直接传递数据
Parent.js文件里(父组件)
import React, { Component } from 'react'
import './Parent.css'
import { Child1 } from './Child1'
import { Child2 } from './Child2'
export class Parent extends Component {
state = {
msg: '',
mag1: ''
}
setMsg = (msg) => {
console.log(msg);
this.setState({
msg: msg
})
}
setMsg1 = (mag1) => {
console.log(mag1);
this.setState({
mag1: mag1
})
}
render() {
return (
// 父组件
<div className="parent">
<h1>父组件</h1>
<Child1 msg={this.state.msg} setMsg1={this.setMsg1} />
<Child2 setMsg={this.setMsg} mag1={this.state.mag1} />
</div>
)
}
}
Child1.js文件了 (子组件1)
import React, { Component } from 'react'
export class Child1 extends Component {
render() {
return (
<div className="child">
<h1>兄弟1 {this.props.msg}</h1>
<button onClick={() => this.props.setMsg1('这就去')}>xx</button>
</div>
)
}
}
Child2.js文件了 (子组件2)
import React, { Component } from 'react'
export class Child2 extends Component {
render() {
return (
<div className="child">
<h1>兄弟2{this.props.mag1}</h1>
<button onClick={() => this.props.setMsg('挨揍了')}>xx</button>
</div>
)
}
}
跨组件传递
import React, { Component } from 'react';
import './App1.css';
// 1 创建 Context 跨组件传值的上下文
const ThemeContext = React.createContext();
const { Provider, Consumer } = React.createContext();
const Node = () => (
<div className="node">
Node
<SubNode />
</div>
);
const SubNode = () => (
<div className="sub-node">
SubNode
<Child />
</div>
);
const Child = () => (
<div className="child">
Child
<hr />
<Consumer>
{(value) => <div style={{ color: value }}>Childxxx</div>}
</Consumer>
</div>
);
export class App1 extends Component {
render() {
return (
<Provider value={'pink'}>
<div className="app">
<h1>我是App组件</h1>
<Node />
</div>
</Provider>
);
}
}
}