简体   繁体   中英

Creating a class in react and exporting with higher order components

I am writing a class in React and exporting it with a higher order component, presently I have ...

import React, { Component } from 'react';
import { withRouter }       from 'react-router';


/**
    Project Editor
*/
class SpiceEditorRaw extends Component { ... }

const SpiceEditor = withRouter(SpiceEditorRaw);    
export default SpiceEditor;

Then In a different file I import SpiceEditor and subclass it with

import SpiceEditor from './SpiceEditor'

class NameEditor extends SpiceEditor {

    constructor(props){ ... } 

    ...
    render () { return (<h1> hello world <h1/>) }

}

However I am getting error:

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.

I believe it is possible to create a compoenent using withRouter , so I must be syntaxing incorrectly?

You should generally not use extends on any other component than React.Component . I think the Composition vs Inheritance part of the documentation is a great read on this subject.

You can accomplish almost everything with composition instead.

Example

import SpiceEditor from './SpiceEditor'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM