简体   繁体   中英

react + redux. can i dispatch an action that will take a component and have another component render it via this.props.children?

Say I have a simple component..

const SimpleComponent = () => {
  return (
    <p>Hello!</p>
  );
}

If I import SimpleComponent into some component, and then dispatch an action like this:

this.props.dispatch(someActionOfMine(SimpleComponent));

How can I have another component render this component inside of it as this.props.children ?

For example, here's AnotherComponent :

class AnotherComponent extends React.Component {
  render() {
    return (
      {React.cloneElement(this.props.children, { ...this.props })}
    );
  }
}

And it might be used like this, in some component's render:

render() {
  return (
    <AnotherComponent>{this.props.somePieceOfState.component}</AnotherComponent>
  );
}

Can this work? I'm trying it but it provides this error:

invariant.js:44 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

Never mind I'm an idiot. You need to pass the component like this: this.props.dispatch(someAction(<SomeComponent />))

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