国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

React進階學習之組件的解耦之道

2024-05-06 15:13:20
字體:
來源:轉載
供稿:網友

前言

眾所周知,React中的組件非常的靈活可擴展,不過隨著業務復雜度的增加和許多外部工具庫的引入,組件往往也會顯得浮腫,接下來我們就一起來看看常見的幾種,遵循單一職責原則的,組件分割與解耦的方法,話不多說了,來一起看看詳細的介紹:

一、分割 render 函數

當一個組件渲染的內容較多時,有一個快速并且通用的方法是創建sub-render函數來簡化原來龐大的 render

class Panel extends React.Component { renderHeading() { // ... } renderBody() { // ... } render() { return ( <div> {this.renderHeading()} {this.renderBody()} </div> ); }}

為了再次簡化sub-render函數,我們還可以采用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() { // ... }}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 甘洛县| 长岛县| 新丰县| 涪陵区| 于都县| 乡城县| 玛沁县| 峡江县| 吉林省| 杨浦区| 乐山市| 舒城县| 濮阳市| 济源市| 贡觉县| 长葛市| 和林格尔县| 全南县| 宾川县| 天祝| 四川省| 孝义市| 蕲春县| 卢氏县| 黔西县| 东明县| 锦州市| 合肥市| 鄂州市| 抚顺市| 当涂县| 应用必备| 班戈县| 安岳县| 南川市| 张家港市| 从化市| 太和县| 通化县| 饶阳县| 阿荣旗|