前言
React 的元件設計非常靈活、易於擴充,但隨著業務複雜度上升、外部工具庫不斷引入,元件往往會變得臃腫。以下整理幾種遵循單一職責原則的元件拆分與解耦做法。
一、拆分 render 函式
當一個元件要渲染的內容很多時,最快也最通用的做法是抽出 sub-render 函式,替龐大的 render 減負。
class Panel extends React.Component { renderHeading() { // ... } renderBody() { // ... } render() { return ( <div> {this.renderHeading()} {this.renderBody()} </div> ); } }
想再往下簡化,可以改用 Functional Components 的寫法。這樣切出的處理單元更小,也更好測試。
const PanelHeader = (props) => ( // ... ); const PanelBody = (props) => ( // ... ); class Panel extends React.Component { render() { return ( <div> // Nice and explicit about which props are used <PanelHeader title={this.props.title}/> <PanelBody content={this.props.content}/> </div> ); } }
二、用 props 傳遞元素
如果一個元件的狀態或配置特別多,可以讓 props 傳遞元素而不只是資料。做法是先宣告一個「模板」元件,讓父元件只專注於組裝。
class CommentTemplate extends React.Component { static propTypes = { // Declare slots as type node metadata: PropTypes.node, actions: PropTypes.node, }; render() { return ( <div> <CommentHeading> <Avatar user={...}/> // Slot for metadata <span>{this.props.metadata}</span> </CommentHeading> <CommentBody/> <CommentFooter> <Timestamp time={...}/> // Slot for actions <span>{this.props.actions}</span> </CommentFooter> </div> ); } }
父元件
class Comment extends React.Component { render() { const metadata = this.props.publishTime ? <PublishTime time={this.props.publishTime} /> : <span>Saving...</span>; const actions = []; if (this.props.isSignedIn) { actions.push(<LikeAction />); actions.push(<ReplyAction />); } if (this.props.isAuthor) { actions.push(<DeleteAction />); } return <CommentTemplate metadata={metadata} actions={actions} />; } }
三、使用高階元件
舉例來說,要監聽元件內的超連結點擊並回報該元件的 ID,常見寫法如下。
class Document extends React.Component { componentDidMount() { ReactDOM.findDOMNode(this).addEventListener('click', this.onClick); } componentWillUnmount() { ReactDOM.findDOMNode(this).removeEventListener('click', this.onClick); } onClick = (e) => { if (e.target.tagName === 'A') { // Naive check for <a> elements sendAnalytics('link clicked', { documentId: this.props.documentId // Specific information to be sent }); } }; render() { // ... } }
問題是這段邏輯無法複用,元件要重構時也很棘手。
高階元件可以解決這些問題。顧名思義,它是一個函式:傳入一個元件,回傳一個新元件。
function withLinkAnalytics(mapPropsToData, WrappedComponent) { class LinkAnalyticsWrapper extends React.Component { componentDidMount() { ReactDOM.findDOMNode(this).addEventListener('click', this.onClick); } componentWillUnmount() { ReactDOM.findDOMNode(this).removeEventListener('click', this.onClick); } onClick = (e) => { if (e.target.tagName === 'A') { // Naive check for <a> elements const data = mapPropsToData ? mapPropsToData(this.props) : {}; sendAnalytics('link clicked', data); } }; render() { // Simply render the WrappedComponent with all props return <WrappedComponent {...this.props} />; } } return LinkAnalyticsWrapper; }
使用起來就清爽多了。
class Document extends React.Component { render() { // ... } } export default withLinkAnalytics((props) => ({ documentId: props.documentId }), Document);
總結
以上三種解耦手法都可以直接套進專案。一開始可能覺得有點不順手,但堅持下去,你會寫出更健壯、更容易複用的程式碼。
以上就是這篇文章的全部內容,希望對你的學習或工作有所幫助。有疑問歡迎留言交流。
原文連結:Techniques for decomposing React components