React之组件通讯

假期在家,继续学习React知识,记录下来,方便查看。

一、组件通讯基本使用

即组件间相互进行数据通讯。组件是独立且封闭的单元,默认情况下 只能使用组件自己的数据,在实际过程中 多个组件不可避免的事要共享某些数据,打破组件的独立封闭性,让其与外界沟通。
组件是封闭的,要接收外部数据应当通过 props 来实现;
props 作用 接收传递给组件的数据
传递数据 给组件标签添加数据
方式一、函数式组件使用
函数组件通过 参数props 来接收数据。

// 接收数据
const Hello = (props) => {
    
    
	console.log(props);
	return(
		<div><h1>props:{
    
    props.name}</h1></div>
	)
}
// 1、传递数据
ReactDOM.render(<Hello name="Tom" age={
    
    20} />,document.getElementById('root'))

方式二、类组件使用
类组件 通过 this.props 接收数据。

// 接收数据
Class Hello extends React.Component{
    
    
	render(){
    
    
		<div><h1>props:{
    
    this.props.name}</h1></div>
	}
}
// 1、传递数据
ReactDOM.render(<Hello name="Jack" age={
    
    18} />,document.getElementById('root'))
二、组件通讯-props 特点

1)可以给组件传递任意类型的数据,如函数、CSS属性等
2)props 是只读对象,只能读取属性的值,无法修改对象
3)使用类组件时,若写了构造函数,则将props传递给super(),否则无法在构造函数中获取到props。

三、组件通讯三种传递方式

1、父组件 -> 子组件
1)父组件提供要传递的state数据;
2)给子组件标签添加属性,值为state中的数据;
3)子组件通过 props 接收父组件中传递的数据。

// 父组件
Class Parent extends React.Component{
    
    
	state = {
    
    
		sayHello: 'hello word'
	}
	render(){
    
    
		<div className="parent">
		父组件<Child name={
    
    this.state.sayHello} />
		</div>
	}
}
const Child = propos => {
    
    
	return (
		<div className="child">
			<p>子组件,接收到父组件的数据:{
    
    props.name}</p>
		</div>
	)
}
// 渲染
ReactDOM.render(<Parent />,document.getElementById('root'))

2、子组件 -> 父组件
3、兄弟组件

猜你喜欢

转载自blog.csdn.net/u012190388/article/details/128598571