How to validate component composition / “base”-com

2019-04-12 20:05发布

It is common knowledge that when we want to "extend" a <Component> in React, we don't actually extend its class via inheritance, but use composition to render it with custom props inside our "derived" component, like this:

class Component extends React.Component {
  render() {
    return (<div className={ this.props.special_prop }>
              I'm a component!
            </div>);
  }
}

class DerivedComponent extends React.Component {
  render() {
    return (<Component special_prop='custom value' />);
  }
}

So this will create a new type of component <DerivedComponent>, which will still render a regular <Component>, but with custom values specified via props.

My question is, is there some way to validate that <DerivedComponent> actually renders a <Component> as its root component / that it is "derived" in that sense from <Component>?

I'm asking because I'm developing a listing component which will render list item components of numerous types in a list, but even though these list item components will be different types, each one will actually render the same root component, just customized with different props. I'd like to enforce, via propTypes or similar, that the children passed to the listing component are actually based on that common root-rendered component.

Had React used classical inheritance, it would just be a trivial matter of checking if each list item instance was also an instance of that common component; however, I do not believe that React has the API to query the root-rendered component of a composition.

Is there some way in React to enforce that the children are based on a specific root-rendered component?

0条回答
登录 后发表回答