前言
眾所周知,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() {
// ...
}
}
然而它卻存在代碼不能復用,組件重構困難等問題
我們可以使用高階組件來解決這些問題,顧名思義,高階組件就是一個函數,傳給它一個組件,它返回一個新的組件
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);
總結
以上 3 個 React 組件的解耦重構方法都可以直接拿來運用,最開始可能會覺得有點棘手,但是沒關系,只要堅持下來,你就會寫出更強壯和可復用的代碼。
好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對的支持。
原文鏈接: Techniques for decomposing React components