组件之间的通讯,props

组件的props  接受传递给组件的数据

// 组件的props
// 函数组件接收数据
// const Hello = (props) => {
// 	// props是一个对象
// 	console.log(props);
// 	return (
// 		<div>
// 			<h1>props:{ props.name }</h1>
// 		</div>
// 	)
// }
// // 传递数据



// 类组件传递数据
class Hello extends React.Component{
	render () {
		console.log(this.props);
		return (
			<div>
				<h1>props:{ this.props.age }</h1>
			</div>
		)
	}
}


reactDom.render(<Hello name="rose" age={19} />,document.getElementById('root'))

 组件的通讯方式   三种方式

1.父组件 -子组件

// 父组件-子组件传值

// 父组件
class Parent extends React.Component{
	state = {
		lastName:'王'
	}
	render () {
		return (
			<div className="parent">
				父组件:
				<Child name={this.state.lastName} />
			</div>
		)
	}
}

// 子组件
const Child = (props) => {
	console.log(props);
	return (
		<div className="child">
			<p>子组件,接收父组件的数据:{ props.name }</p>
		</div>
	)
}

reactDom.render(<Parent />,document.getElementById('root'))

2.子组件-父组件

// 父组件
class Parent extends React.Component{
	state = {
		Parmsg:''
	}
	// 提供回调函数,接收数据
	getChildMsg = data => {
		console.log('子组件传递过来的数据', data);
		this.setState({
			Parmsg:data
		})
	}
	render () {
		return (
			<div>
				父组件:{this.state.Parmsg}
				<Child getMsg={this.getChildMsg} />
			</div>
		)
	}
}
// 子组件
class Child extends React.Component{
	state = {
		msg:'刷抖音'
	}
	handleclick = () => {
			this.props.getMsg(this.state.msg)
	}
	render () {
		return (
			<div>
					子组件:<button onClick={this.handleclick}>点我给父组件传值</button>
			</div>
		)
	}
}
reactDom.render(<Parent />,document.getElementById('root'))

3.兄弟组件

class Counter extends React.Component{
	// 提供共享状态
	state = {
		count:0
	}
	// 提供修改状态的方法
	onIncrement = () => {
		this.setState({
			count:this.state.count+1
		})
	}
	render () {
		return (
			<div>
				<Child1 count={this.state.count} />
				<Child2 onIncrement={this.onIncrement} />
			</div>
		)
	}
}

const Child1 = (props) => {
	return <h1>计数器:{ props.count}</h1>
}
const Child2 = (props) => {
	return <button onClick={()=>props.onIncrement()}>+1</button>
}

reactDom.render(<Counter/>,document.getElementById('root'))

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值