1.父组件向子组件传值(通过props)
(1)、子组件child.js
import React from "react";
export default class Child extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div style={{ color: "red" }}>
<div>
{this.props.name}
</div>
</div>
)
}
}
(2)、父组件father.js
import React from "react"
import Child from "./child"
export default class Father extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<Child name="abc"></Child>
</div>
)
}
}
2.子组件向父组件传值(回调函数)
(1)、子组件
import React from "react";
export default class Child extends React.Component {
constructor(props) {
super(props)
}
handleClick() {
let color = this.props.bgColor == "green" ? "#999" : "green"
this.props.changeBgColor(color)
}
render() {
return (
<div style={{ color: "red" }}>
<div>
{/* 2. 子组件给父组件传值*/}
{/* 子组件接收父组件的背景颜色值 */}
<div>父组件的背景色{this.props.bgColor}</div>
{/* 子组件执行改变颜色的函数 */}
<button onClick={(e) => { this.handleClick(e) }}>改变父组件的背景色</button>
</div>
</div>
)
}
}
(2)、父组件
import React from "react"
import Child from "./child"
export default class Father extends React.Component {
constructor(props) {
super(props)
this.state = {
bgColor: "#999",
}
}
bgChange(color) {
this.setState({
bgColor: color
})
}
render() {
return (
<div style={{ background: this.state.bgColor }}>
<Child bgColor={this.state.bgColor} changeBgColor={(color) => { this.bgChange(color) }}></Child>
{/* 父组件给子组件传值方法 */}
</div>
)
}
}
3.兄弟组件传值(兄弟组件1传值给父组件,父组件在通过props传值给兄弟组件2)
(1)、brother1.js
import React from "react"
export default class Brother1 extends React.Component {
constructor(props) {
super(props)
}
handleClick() {
// 改变兄弟的背景
let color = this.props.color == "green" ? "yellow" : "green"
this.props.changeColor(color)
}
render() {
return (
<div>
<div>brother1</div>
<button onClick={(e) => { this.handleClick(e) }}>改变brother2的背景</button>
</div>
)
}
}
(2)、brother2.js
import React from "react"
export default class Brother2 extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div style={{ background: this.props.color }}>
<div>
brother2的背景色{this.props.color}
</div>
</div>
)
}
}
(3)、父组件
import React from "react"
import Brother1 from "./brother1";
import Brother2 from "./brother2";
export default class Father extends React.Component {
constructor(props) {
super(props)
this.state = {
color: "yellow"
}
}
colorChange(color) {
this.setState({
color: color
})
}
render() {
return (
<div>
<Brother1 color={this.state.color} changeColor={(color) => { this.colorChange(color) }}></Brother1>
<Brother2 color={this.state.color}></Brother2>
</div>
)
}
}