FP替代JavaScript/ReactJS中的多态

Wan*_*eho 9 javascript functional-programming ecmascript-6 reactjs

我目前正在开发一个ReactJS项目,我需要创建"可重用"组件,其中一些方法需要被"覆盖".在OOP中我会使用多态.我已经做了一些阅读,似乎共识是使用HoC /组合但我无法弄清楚如何实现这一目标.我想如果我可以使用合成得到一个ES6样本,那么之后可能更容易将这个想法改编为ReactJS.

下面是我想在ReactJS中实现的ES6 OOP示例(忽略处理它仅用于测试的事件).有没有人对如何将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();
Run Code Online (Sandbox Code Playgroud)
<div id="content"></div>
<div id="message"></div>
Run Code Online (Sandbox Code Playgroud)

更新: 尽管我的原始问题是关于FP我认为渲染道具是我的问题的一个非常好的解决方案,并避免了HoC问题.

bsa*_*aka 5

编辑:

此帖子已过时。Hook 更适合大多数用例。

原答案:

有关示例代码的答案位于本文的中间/底部。

React 组合的一个好方法是渲染回调模式,也称为子函数。与 HOC 相比,它的主要优点是它允许您在运行时(例如在渲染中)动态地组合组件,而不是在创作时静态地组合组件。

无论您使用渲染回调还是 HOC,组件组合的目标都是将可重用行为委托给其他组件,然后将这些组件作为 props 传递给需要它们的组件。

摘要示例:

以下Delegator组件使用渲染回调模式将实现逻辑委托给ImplementationComponent作为 prop 传入的组件:

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

各种实现组件如下所示:

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 })
  }
} 
Run Code Online (Sandbox Code Playgroud)

稍后,您可以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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,嵌套子组件允许多种具体实现:

const App = () => (
  <div>
    <Delegator 
      ImplementationComponent={ImplementationB}
      AnotherImplementation={AnotherImplementation1}
      SomethingElse={SomethingVariationY}
    />

    <Delegator 
      ImplementationComponent={ImplementationC}
      AnotherImplementation={AnotherImplementation2}
      SomethingElse={SomethingVariationZ}
    />
  </div>
); 
Run Code Online (Sandbox Code Playgroud)

回答(你的例子):

将上述组合模式应用到您的示例中,该解决方案会重组您的代码,但假设它需要执行以下操作:

  • 允许输入及其验证逻辑的变化
  • 当用户提交有效输入时,然后执行一些ajax

首先,为了让事情变得更容易,我将 DOM 更改为:

<div id="content-inputs"></div>
<div id="content-button"></div> 
Run Code Online (Sandbox Code Playgroud)

现在,TransferComponent只知道如何显示按钮并在按下按钮且数据有效时执行某些操作。它不知道要显示哪些输入或如何验证数据。它将该逻辑委托给嵌套的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>
    )
  }
};
Run Code Online (Sandbox Code Playgroud)

现在我们创建具体的实现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 });
  }
}
Run Code Online (Sandbox Code Playgroud)

用户名和密码的实现:

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 });
  }
}
Run Code Online (Sandbox Code Playgroud)

最后,编写 的实例TansferComponent如下所示:

<TransferComponent VaryingComponent={UsernameComponent} />
<TransferComponent VaryingComponent={UsernamePasswordComponent} />
Run Code Online (Sandbox Code Playgroud)