react 子传参父_react 中父传子,子传父,以及兄弟组件传参问题

父组件向子组件传值(通过props传值)

子组件:

class Children extends Component{

constructor(props){

super(props);

}

render(){

return(

这是:{this.props.name}
// 这是 父向子

)

}

}

父组件:

class App extends React.Component{

render(){

return(

)

}

}

父组件向子组件传值(回调函数)

子组件:

class Children extends Component{

constructor(props){

super(props);

}

handerClick(){

this.props.changeColor('skyblue') // 执行父组件的changeColor 并传参 必须和父组件中的函数一模一样

}

render(){

return(

父组件的背景色{this.props.bgcolor}
// 子组件接收父组件传过来的值 bgcolor

{this.handerClick(e)}}>改变父组件背景 // 子组件执行函数

)

}

}

父组件

class Father extends Component{

constructor(props){

super(props)

this.state = {

bgcolor:'pink'

}

}

bgChange(color){

this.setState({

bgcolor:color

})

}

render(props){

// 给子组件传递的值 color

{this.bgChange(color)}} />

// changeColor 子组件的参数=color 当做形参

}

}

兄弟组件传值(子传给父,父再传给另一个子)

子组件1

class Children1 extends Component{

constructor(props){

super(props);

}

handerClick(){

this.props.changeChild2Color('skyblue')

// 改变兄弟组件的颜色 把changeChild2Color的参数传给父

}

render(){

return(

children1

{this.handerClick(e)}}>改变children2背景

)

}

}

子组件2

class Children2 extends Component{

constructor(props){

super(props);

}

render(){

return(

// 从父元素获取自己的背景色

children2 背景色 {this.props.bgcolor}

// children2 背景色 skyblue

)

}

}

父组件

class Father extends Component{

constructor(props){

super(props)

this.state = {

child2bgcolor:'pink'

}

}

onchild2bgChange(color){

this.setState({

child2bgcolor:color

})

}

render(props){

{this.onchild2bgChange(color)}} />

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值