代码之家  ›  专栏  ›  技术社区  ›  xiaolingxiao

在react中创建类并使用高阶组件导出

  •  2
  • xiaolingxiao  · 技术社区  · 7 年前

    我正在react中编写一个类,并用一个更高阶的组件导出它,目前我已经…

    import React, { Component } from 'react';
    import { withRouter }       from 'react-router';
    
    
    /**
        Project Editor
    */
    class SpiceEditorRaw extends Component { ... }
    
    const SpiceEditor = withRouter(SpiceEditorRaw);    
    export default SpiceEditor;
    

    然后在另一个文件中导入 SpiceEditor 并将其与

    import SpiceEditor from './SpiceEditor'
    
    class NameEditor extends SpiceEditor {
    
        constructor(props){ ... } 
    
        ...
        render () { return (<h1> hello world <h1/>) }
    
    }
    

    但是我有个错误:

    index.js:2178 Warning: The <withRouter(SpiceEditorRaw) /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change withRouter(SpiceEditorRaw) to extend React.Component instead.
    

    我相信有可能创造一个 compoenent 使用 withRouter 所以我必须同步错误吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Tholle    7 年前

    你一般不应该使用 extends 在除 React.Component 是的。我认为 Composition vs Inheritance 文件的一部分是关于这个问题的大量阅读。

    你可以用作文来完成几乎所有的事情。

    例子

    import SpiceEditor from './SpiceEditor'
    
    class NameEditor extends React.Component {
      render () {
        return (
          <SpiceEditor>
            { /* ... */ }
          </SpiceEditor>
        )
      }
    }