矩形扩展中间件

Rect extend middleware

首先,我是来了解 php 背景知识的,目前我正在构建一个 React 中间件,我的做法是这样的:

class Middleware extends React.Component {
  funcOne(data) {
    return data;
  }

  funcTwo(data) {
    return (
      <div>
        { data }
        <br />
        { this.funcThree('Third function') }
      </div>
    );
  }
}

class MyComponent extends Middleware {
  funcOne(data) {
    return `Rewrite of ${data}`;
  }

  funcThree(data) {
    return data;
  }

  render() {
    return (
      <div>
        { this.funcOne('First function') }
        { this.funcTwo('Second function') }
      </div>
    );
  }
}

class MySecondComponent extends Middleware {
  funcThree(data) {
    return data;
  }

  render() {
    return (
      <div>
        { this.funcOne('First function') }
        { this.funcTwo('Second function') }
      </div>
    );
  }
}

ReactDOM.render(
  <div>
    <MyComponent />
    <hr />
    <MySecondComponent />
  </div>,
  document.getElementById('root'),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="root"></div>

但是我真的找不到任何关于是否要这样做的文档。 那么,这是错误的吗? 如果是这样,我应该怎么做呢?

您要实现的通常称为高阶组件。 Here 是详细文档。

在您更新的代码中,只需为 funcTwo 创建一个组件并向其传递一个道具:

function funcOne () {
  return 'First function';
}

function Two (props) {
  return (
    <div>
      Second function
      <br />
      { props.three }
    </div>
  );
}

//...

  render() {
    return (
      <div>
        { funcOne() }
        <br />
        <Two three={this.funcThree()} />
      </div>
    );
  }

我从未见过任何必须在 React 中使用继承的用例。在您的情况下,只需创建组件或普通函数。此外,一个组件也可以是一个普通的函数:

这可以是一个组件:

function One (props) {
  return <h1>hello</h1>
}

你这样使用它:

<One />

或者,如果您只需要字符串,只需编写函数:

function funcOne () {
  return 'First function';
}

function funcTwo () {
  return 'Second function';
}

// ...

  render() {
    return (
      <div>
        { funcOne() }
        <br />
        { funcTwo() }
      </div>
    );
  }

因此你根本不需要继承。在 JavaScript 中,尤其是 React,你应该尝试以更函数式的方式思考。你会发现它非常强大和灵活。

您可以在此处找到有关组件组合的官方文档:https://facebook.github.io/react/docs/composition-vs-inheritance.html

我也推荐你阅读这个:https://facebook.github.io/react/docs/thinking-in-react.html

我认为您在 React 世界中进行重用的方式是通过创建采用组件的函数和 return 具有附加功能的新组件,将其包装在为其添加功能的组件中。

这可以通过将您想要 "derive" 功能的组件传递给函数或直接将其包装在 "wrapper" 组件中并访问 "wrapped" 组件来完成在 props.children 属性.

const componentWithDropTargetCapabilities = addDragAndDrop(MyComponent)

<DropTarget>
   <MyComponent />
</DropTarget>

这些被称为 "higher order components" (HOC) : https://facebook.github.io/react/docs/higher-order-components.html

看一下 ar react-router 代码例如:https://github.com/ReactTraining/react-router