React组件通讯的三种方式
- 父组件传递数据给子组件
- 子组件传递数据给父组件
React组件之间的通讯分为三种:
- 父组件 →子组件
- 子组件 →父组件
- 兄弟组件
父组件传递数据给子组件
步骤:
- 父组件提供要传递的state数据
- 给子组件标签添加属性,值为state中的数据
- 子组件中通过props接收父组件中传递的数据
项目演示:
使用脚手架生成一个React项目: npx create-react-app ex-app
运行项目:npm start
目录结构如下:
index.js中的代码:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';// 父传子
// 父组件
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>)
}const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( <Parent / >
);// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
子组件传递数据给父组件
思路:利用回调函数,父组件提供回调,子组件调用,将要传递的数据作为回调函数的参数。
- 父组件提供一个回调函数(用于接收数据)
- 将该函数作为属性的值,传递给子组件
- 子组件通过props调用回调函数
- 将子组件的数据作为参数传递给回调函数