🧩 第一章:組件通訊概述
在 React 開發中,組件是封裝的、獨立的功能單元。為了實現組件間的數據共享與協作,需要通過組件通訊機制。
組件通訊的意義:
讓多個封閉的組件能夠共享數據,實現協作功能。
📥 第二章:組件 Props 基礎與進階
1. Props 的基本使用
組件是封閉的,要接收外部數據應通過 props(屬性) 實現。
? 使用方式:
- 傳遞數據:給組件標簽添加屬性
- 接收數據:
- 函數組件:通過參數?
props
?接收 - 類組件:通過?
this.props
?接收
- 函數組件:通過參數?
? 示例:
<Hello name="jack" age={19} />
// 函數組件
function Hello(props) {return <div>接收到數據:{props.name}</div>;
}
// 類組件
class Hello extends React.Component {render() {return <div>接收到數據:{this.props.age}</div>;}
}
2. Props 的特點
可傳遞任意類型數據
<Helloname="root"age={19}colors={['red', 'blue']}fn={() => console.log('函數')}tag={<h1>標簽</h1>} />
只讀對象
props 是只讀的,不能直接修改。構造函數中使用 props
如果類組件有構造函數,必須將 props 傳入super()
,否則無法在構造函數中訪問 props。constructor(props) {super(props); }
3. 組件通信的三種方式
? 1. 父組件 → 子組件
步驟:
- 父組件通過?
state
?傳遞數據 - 子組件通過?
props
?接收數據
class Parent extends React.Component {state = { lastName: "王" };render() {return <Child name={this.state.lastName} />;}
}
function Child(props) {return <div>子組件接收到數據:{props.name}</div>;
}
? 2. 子組件 → 父組件
使用回調函數實現:
- 父組件定義回調函數,并傳給子組件
- 子組件調用回調,傳入數據
class Parent extends React.Component {getChildMsg = (msg) => {console.log("接收到子組件數據", msg);};render() {return <Child getMsg={this.getChildMsg} />;}
}
class Child extends React.Component {state = { childMsg: "react" };handleClick = () => {this.props.getMsg(this.state.childMsg);};return <button onClick={this.handleClick}>點擊傳值</button>;
}
? 3. 兄弟組件通信
核心思想:狀態提升(Lifting State Up)
- 將共享狀態提升到公共父組件
- 父組件提供狀態和更新方法
- 子組件通過 props 接收并使用
class App extends React.Component {state = { count: 0 };handleClick = () => {this.setState({ count: this.state.count + 1 });};render() {return (<div><Zi num={this.state.count} /><Zi2 numadd={this.handleClick} /></div>);}
}
function Zi(props) {return <div>count: {props.num}</div>;
}function Zi2(props) {return <button onClick={props.numadd}>Click Me</button>;
}
? 4. Context 組件(跨層級通信)
當組件嵌套較深或為“遠方親戚”時,使用 Context
實現通信更高效。
使用步驟:
- 創建?
Provider
?和?Consumer
const { Provider, Consumer } = React.createContext();
- 使用?
Provider
?提供數據
<Provider value="pink"><div className="APP"><Child /></div>
</Provider>
- 使用?
Consumer
?消費數據
<Consumer>{data => <span>數據為:{data}</span>}
</Consumer>
🧠 第三章:Props 深入理解
1.?children
?屬性
表示組件標簽的子節點,可以是任意類型:文本、React 元素、組件、甚至是函數。
function Hello(props) {return <div>組件的子節點:{props.children}</div>;
}
<Hello>我是子節點</Hello>
2. Props 校驗(PropTypes)
使用 prop-types
包進行類型校驗,確保組件接收的數據符合預期。
安裝:
npm install prop-types
使用:
import PropTypes from 'prop-types';App.propTypes = {colors: PropTypes.array,fn: PropTypes.func.isRequired,shape: PropTypes.shape({id: PropTypes.number,name: PropTypes.string})
};
3. Props 默認值(defaultProps)
設置默認值,防止 props 未傳時出錯。
App.defaultProps = {pageSize: 10
};
function App(props) {return <div>默認值:{props.pageSize}</div>;
}
🕒 第四章:組件生命周期詳解
組件的生命周期分為三個階段:創建、更新、卸載,每個階段都有對應的鉤子函數。
1. 創建階段(Mounting)
執行時機:組件創建時(頁面加載時)
執行順序:
constructor → render() → componentDidMount
constructor
:初始化 state,綁定 thisrender
:渲染 UI(不能調用?setState
)componentDidMount
:組件掛載后,適合發送網絡請求、DOM 操作
constructor(props) {super(props);this.state = { count: 0 };
}
componentDidMount() {console.log('組件已掛載');
}
2. 更新階段(Updating)
執行時機:組件更新時(如調用 setState()
、forceUpdate()
或接收到新的 props)
執行順序:
render() → componentDidUpdate()
render
:重新渲染 UIcomponentDidUpdate
:組件更新后,適合發送網絡請求、DOM 操作
componentDidUpdate(prevProps, prevState) {if (prevState.count !== this.state.count) {console.log('組件已更新');}
}
3. 卸載階段(Unmounting)
執行時機:組件從頁面消失
執行函數:
componentWillUnmount() {// 清理工作,如清除定時器、取消訂閱等
}
📚 總結
模塊 | 內容 |
---|---|
組件通訊 | Props、回調函數、Context、狀態提升 |
Props | 傳遞任意類型數據、只讀、children、校驗、默認值 |
生命周期 | 創建、更新、卸載階段,各階段鉤子函數用途 |