1. 父传子
- 在父组件 Parent.js 中
父组件通过在在组件标签上绑定属性来传参
import React, { Component } from "react";
import Child1 from "./Child1";
const params = {
content1: "云想衣裳",
content2: "花想容",
};
export default class Parent extends Component {
render() {
return (
<div>
<Child1 params={params} />
</div>
);
}
}
- 在子组件 Child1.js 中
子组件通过 props 属性 来接收参数
import React, { Component } from "react";
export default class Child1 extends Component {
constructor(props) {
super(props);
this.state = props.params;
}
render() {
return (
<>
<div>
{this.props.params.content1 + this.props.params.content2} <br />
{this.state.content1 + this.state.content2}
</div>
</>
);
}
}
2. 子传父
- 在父组件 Parent.js 中
父组件通过在在组件标签上绑定子组件定义的方法属性(形参是接收的参数)来接收参
import React, { Component } from "react";
import Child1 from "./Child1";
export default class Parent extends Component {
constructor(props) {
super(props);
this.state = {
content1: "云想衣裳花想容",
};
}
render() {
return (
<div>
<Child1
changeContent={(arg) => {
this.setState({
content1: (this.state.content1 += "," + arg),
});
}}
/>
<div>{this.state.content1}</div>
</div>
);
}
}
- 在子组件 Child1.js 中
子组件通过在 props 属性上添加自定义的方法来向父组件传递参数
import React, { Component } from "react";
export default class Child1 extends Component {
constructor(props) {
super(props);
this.state = {
content1: "春风拂槛露华浓",
};
}
render() {
return (
<>
<div>
<button
onClick={this.props.changeContent.bind(this, this.state.content1)}
>
子组件按钮
</button>
</div>
</>
);
}
}
3. 兄弟组件传值
需要使用 pubsub-js,没有的情况下需要安装
npm install pubsub-js -S
- 在子组件 Child1.js 中
引入 pubsub-js,通过 PubSub.publish("自定义事件名称", 参数) 发送事件和参数
import React, { Component } from "react";
import PubSub from "pubsub-js";
export default class Child1 extends Component {
constructor(props) {
super(props);
this.state = {
content1: "春风拂槛露华浓",
};
}
changeChild2Content() {
PubSub.publish("changeChild2ContentFun", this.state.content1);
}
render() {
return (
<>
<div>
<button onClick={this.changeChild2Content.bind(this)}>
Child1按钮
</button>
</div>
</>
);
}
}
- 在子组件 Child2.js 中
引入 pubsub-js,通过 PubSub.subscribe("事件名称", (事件名称, 接收的参数) => {})
import React, { Component } from "react";
import PubSub from "pubsub-js";
export default class Child2 extends Component {
constructor(props) {
super(props);
this.state = {
content1: "云想衣裳花想容",
};
PubSub.subscribe("changeChild2ContentFun", (functionName, arg) => {
console.log(functionName, arg);
this.setState({
content1: "春风拂槛露华浓",
});
});
}
render() {
return (
<>
<div>{this.state.content1}</div>
</>
);
}
}
注意: 如果在严格模式下,开发环境下事件会触发两次,线上环境则正常只会触发一次
如果在开发环境也调用一次,需要去除严格模式
在入口文件 index.js 下
ReactDOM.render(
// <React.StrictMode>
// <App />
// </React.StrictMode>,
<App />,
document.getElementById("root")
);










网友评论