一、父传子
1、父组件
import React from "react";
import Child from "./child";
export default class father extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "张三",
};
}
render() {
return (
<div>
father
<Child fatherData={this.state.name} ></Child>
</div>
);
}
}
2、子组件
import React from "react";
export default class father extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
console.log(this.props);
}
render() {
return (
<div> child</button>
</div>
);
}
}
二、子传父
父组件定义方法,传给子组件,子组件调用
1、父组件
import React from "react";
import Child from "./child";
export default class father extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "张三",
data:''
};
}
fatherFunction(i) {
console.log(i);
}
render() {
return (
<div>
father
<Child func={this.fatherFunction.bind(this)}></Child>
</div>
);
}
}
1、子组件
import React from "react";
export default class father extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<button onClick={() => { this.props.func(6666); }} > 子传父 </button>
</div>
);
}
}
三、兄弟组件传值
npm i --save pubsub-js
1、brother1(发送)
import React from "react";
import PubSub from "pubsub-js";
export default class father extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
pubsub() {
//PubSub.publish向外定义方法名 第一个参数是方法名,第二个参数是传递的数据
PubSub.publish("methodName", "好兄弟");
}
render() {
return (
<div>
<button onClick={() => { this.pubsub(); }} > 发给我兄弟 </button>
</div>
);
}
}
2、brother2(接收)
import React from "react";
import PubSub from "pubsub-js";
export default class father extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
PubSub.subscribe("methodName", (msg, data) => {
console.log(data);
});
}
render() {
return (
<div>brother2</div>
);
}
}