當使用 TypeScript 在 React 中處理類別元件時,經常被問到是否有必要且強制在建構函式中定義 props 和 state 的問題。這個問題的答案取決於組件的特定需求。在這篇文章中,我們將了解何時以及為何使用建構子來定義 props 和狀態,以及不同方法的優缺點。
1。基於props的狀態初始化:
如果狀態依賴 props 或在初始化狀態時需要執行額外的邏輯,建構函式是最好的選擇。
2.設定初始狀態值:
當你想要設定元件的初始狀態時,建構函式是傳統的方法。
例子:
interface IMyComponentProps { initialCount: number; } interface IMyComponentState { count: number; } class MyComponent extends React.Component{ constructor(props: IMyComponentProps) { super(props); this.state = { count: props.initialCount, }; } render() { return Count: {this.state.count}; } }
1。簡單狀態初始化:
如果state不複雜,不依賴props,可以使用直接狀態初始化,無需建構函數。
2.不需要複雜的邏輯:
如果不需要執行與 props 或 state 相關的額外邏輯,可以直接在類別層級設定 state。
例子:
interface IMyComponentProps { message: string; } interface IMyComponentState { count: number; } class MyComponent extends React.Component{ state: IMyComponentState = { count: 0, }; render() { return Count: {this.state.count}; } }
優點:
缺點:
優點:
缺點:
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3