[英]Sharing React component logic between separate renders
我希望單獨的無狀態組件的render方法可以訪問組件的邏輯。
原因是該應用程序的桌面版本將使用相同的邏輯和類方法,但其呈現方式將有所不同。
class Logic {
constructor() {
this.greeting = 'Buongiorno'
}
showCats() {
return 'Mittens and Puss'
}
}
const Desktop = () => {
return <div style={{ fontSize: 30 }}>
{this.showCats()}
{this.greeting}
</div>
}
const Mobile = () => {
return <div style={{ fontSize: 15 }}>
{this.greeting}
{this.showCats()}
</div>
}
因此,我試圖將類“粘合”到功能組件中。
我可以在不將道具傳遞給無狀態組件的情況下執行此操作嗎?
無狀態組件如何訪問Logic
類中的方法和變量?
我知道我可以使Desktop
和Mobile
狀態組件extend
Logic
類,但是我不確定這是最好的做法。
function Logic(wrappedComponent) {
showCats() {
return 'Mittens and Puss'
}
return (
<wrappedComponent
greetings="Buongiorno"
showCats=showCats
>
{this.props.children}
<wrappedComponent />
)
}
const Desktop = () => {
return <div style={{ fontSize: 30 }}>
{this.props.greeting}
{this.props.showCats()}
</div>
}
export default Logic(Desktop)
const Mobile = () => {
return <div style={{ fontSize: 15 }}>
{this.props.greeting}
{this.props.showCats()}
</div>
}
export default Logic(Mobile)
通常使用高階組件來保持不同組件之間的通用功能。請在此處詳細了解https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e#.do3h4kouk
該任務可以通過使用“高階分量”方法來解決。 您的HoC可能如下所示:
"use strict";
import React, {Component} from "react";
const getDisplayName = (Component) => Component.displayName || Component.name || 'Component';
/**
* Higher order component to inject logic into provided component
*/
export const withLogic = Component => {
class WithLogic extends Component {
//noinspection JSUnusedGlobalSymbols
static displayName = `WithLogic(${getDisplayName(Component)})`;
get logic() {
if (!this._logic) {
this._logic = new Logic();
}
return this._logic;
}
render() {
return <Component {...this.props} />;
}
}
return WithLogic;
};
它的用途是一種合成模式,廣泛用於React:
export default withLogic(Mobile);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.