我目前正在做一个 ReactJS 项目,我需要创建“可重复使用”的组件,其中一些方法需要被“覆盖”。在 OOP 中,我会使用多态性。我读过一些书,似乎共识是使用 HoC/composition,但我不太清楚如何实现这一点。我想如果我可以使用组合获得一个 ES6 示例,那么之后将这个想法应用到 ReactJS 可能会更容易。
下面是一个 ES6 OOP 示例(忽略事件处理,它只是为了测试)几乎是我想在 ReactJS 中实现的。有没有人对如何将 ReactJS 组件分解为 HoC 有一些指导,或者甚至只是演示我将如何根据示例在 ES6 中使用组合?
class TransferComponent {
constructor(){
let timeout = null;
this.render();
this.events();
}
events(){
let scope = this;
document.getElementById('button').addEventListener('click', function(){
scope.validate.apply(scope);
});
}
validate(){
if(this.isValid()){
this.ajax();
}
}
isValid(){
if(document.getElementById('username').value !== ''){
return true;
}
return false;
}
ajax(){
clearTimeout(this.timeout);
document.getElementById('message').textContent = 'Loading...';
this.timeout = setTimeout(function(){
document.getElementById('message').textContent = 'Success';
}, 500);
}
render(){
document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
<button id="button" type="button">Validate</button>';
}
}
class OverrideTransferComponent extends TransferComponent{
isValid(){
if(document.getElementById('username').value !== '' && document.getElementById('password').value !== ''){
return true;
}
return false;
}
render(){
document.getElementById('content').innerHTML = '<input type="text" id="username" value="username"/>\n\
<input type="text" id="password" value="password"/>\n\
<button id="button" type="button">Validate</button>';
}
}
const overrideTransferComponent = new OverrideTransferComponent();
<div id="content"></div>
<div id="message"></div>
更新: 尽管我最初的问题是关于 FP,但我认为渲染 Prop 是解决我的问题的一个很好的解决方案,并且避免了 HoC 问题。
最佳答案
编辑:
这篇文章已经过时了。对于大多数用例, Hook 更好。
原答案:
关于您的示例代码的答案在本文的中间/底部。
关于 React 组合的一个好方法是 render-callback pattern ,又名函数作为 child 。与 HOC 相比,它的主要优势在于它允许您在运行时动态组合组件(例如在渲染中),而不是在创作时静态组合。
无论您是使用渲染回调还是 HOC,组件组合的目标都是将可重用行为委托(delegate)给其他组件,然后将这些组件作为 props 传递给需要它们的组件。
抽象例子:
以下 Delegator
组件使用渲染回调模式将实现逻辑委托(delegate)给作为 prop 传入的 ImplementationComponent
:
const App = () => <Delegator ImplementationComponent={ImplementationB} />;
class Delegator extends React.Component {
render() {
const { ImplementationComponent } = this.props;
return (
<div>
<ImplementationComponent>
{ ({ doLogic }) => {
/* ... do/render things based on doLogic ... */
} }
</ImplementationComponent>
</div>
);
}
}
各种实现组件如下所示:
class ImplementationA extends React.Component {
doSomeLogic() { /* ... variation A ... */ }
render() {
this.props.children({ doLogic: this.doSomeLogic })
}
}
class ImplementationB extends React.Component {
doSomeLogic() { /* ... variation B ... */ }
render() {
this.props.children({ doLogic: this.doSomeLogic })
}
}
稍后,您可以按照相同的组合模式在 Delegator
组件中嵌套更多子组件:
class Delegator extends React.Component {
render() {
const { ImplementationComponent, AnotherImplementation, SomethingElse } = this.props;
return (
<div>
<ImplementationComponent>
{ ({ doLogic }) => { /* ... */} }
</ImplementationComponent>
<AnotherImplementation>
{ ({ doThings, moreThings }) => { /* ... */} }
</AnotherImplementation>
<SomethingElse>
{ ({ foo, bar }) => { /* ... */} }
</SomethingElse>
</div>
);
}
}
现在嵌套子组件允许多个具体实现:
const App = () => (
<div>
<Delegator
ImplementationComponent={ImplementationB}
AnotherImplementation={AnotherImplementation1}
SomethingElse={SomethingVariationY}
/>
<Delegator
ImplementationComponent={ImplementationC}
AnotherImplementation={AnotherImplementation2}
SomethingElse={SomethingVariationZ}
/>
</div>
);
答案(你的例子):
将上述组合模式应用于您的示例,该解决方案重构了您的代码,但假定它需要执行以下操作:
- 允许输入及其验证逻辑的变化
- 当用户提交有效输入时,然后做一些ajax
首先,为了让事情更简单,我将 DOM 更改为:
<div id="content-inputs"></div>
<div id="content-button"></div>
现在,TransferComponent
只知道如何显示按钮并在按钮被按下且数据有效时执行某些操作。它不知道要显示什么输入或如何验证数据。它将逻辑委托(delegate)给嵌套的 VaryingComponent
。
export default class TransferComponent extends React.Component {
constructor() {
super();
this.displayDOMButton = this.displayDOMButton.bind(this);
this.onButtonPress = this.onButtonPress.bind(this);
}
ajax(){
console.log('doing some ajax')
}
onButtonPress({ isValid }) {
if (isValid()) {
this.ajax();
}
}
displayDOMButton({ isValid }) {
document.getElementById('content-button').innerHTML = (
'<button id="button" type="button">Validate</button>'
);
document.getElementById('button')
.addEventListener('click', () => this.onButtonPress({ isValid }));
}
render() {
const { VaryingComponent } = this.props;
const { displayDOMButton } = this;
return (
<div>
<VaryingComponent>
{({ isValid, displayDOMInputs }) => {
displayDOMInputs();
displayDOMButton({ isValid });
return null;
}}
</VaryingComponent>
</div>
)
}
};
现在我们创建 VaryingComponent
的具体实现来充实各种输入显示和验证逻辑。
仅用户名的实现:
export default class UsernameComponent extends React.Component {
isValid(){
return document.getElementById('username').value !== '';
}
displayDOMInputs() {
document.getElementById('content-inputs').innerHTML = (
'<input type="text" id="username" value="username"/>'
);
}
render() {
const { isValid, displayDOMInputs } = this;
return this.props.children({ isValid, displayDOMInputs });
}
}
用户名和密码实现:
export default class UsernamePasswordComponent extends React.Component {
isValid(){
return (
document.getElementById('username').value !== '' &&
document.getElementById('password').value !== ''
);
}
displayDOMInputs() {
document.getElementById('content-inputs').innerHTML = (
'<input type="text" id="username" value="username"/>\n\
<input type="text" id="password" value="password"/>\n'
);
}
render() {
const { isValid, displayDOMInputs } = this;
return this.props.children({ isValid, displayDOMInputs });
}
}
最后,TansferComponent
的组合实例将如下所示:
<TransferComponent VaryingComponent={UsernameComponent} />
<TransferComponent VaryingComponent={UsernamePasswordComponent} />
关于javascript - FP 替代 JavaScript/ReactJS 中的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47232961/