gpt4 book ai didi

javascript - 在单独的渲染之间共享 React 组件逻辑

转载 作者:行者123 更新时间:2023-12-01 02:40:12 25 4
gpt4 key购买 nike

我希望单独的无状态组件的 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>
}

所以我试图将类“粘合”到功能组件上。

我可以在不将 props 传递到无状态组件的情况下执行此操作吗?

无状态组件如何访问Logic类中的方法和变量?

我知道我可以制作DesktopMobile有状态组件来扩展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

关于javascript - 在单独的渲染之间共享 React 组件逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47617757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com