Changing components based on url with react router

北慕城南 提交于 2019-12-04 07:14:19

I feel what you are doing is perfectly fine. You are on the right path.

There's a combination of APIs that React provides you with that will take care of exactly what you're not certain about of how to achieve ( way to pass props to components rendered by this.props.children )

First, you need to take a look at cloneElement

It will basically take a React element, clone it, and return another with props that you can change, alter or replace entirely based on your needs.

Furthermore, combine it with the Children Utilities - loop through the children that were provided to your top level component and make the necessary changes to each element individually.

A proposed sample usage could be as simple as

<div className='main-content'>
    {React.children.map(this.props.children, (child, index) => {
       //Get props of child
       const childProps = child.props;

       //do whatever else you need, create some new props, change existing ones
       //store them in variables

       return React.cloneElement(child, {
           ...childProps, //these are the old props if you don't want them changed
           ...someNewProps,
           someOldPropOverwritten, //overwrite some old the old props 
       });
     )}
</div>

Use these tools to create truly generic and re-usable components, anywhere. More commonly used utilities from Children are map, forEach and toArray. Each with their own respective goals.

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!