Because we have to take over the maintenance of some projects, the team's technology stack has recently switched from Vue to React. As a React novice, and because I always like to learn new things through source code, I chose to learn some usage of React by reading the source code of the famous project antd. While reading the source code, I found that many components used the React.cloneElement API. Although I could guess what it did from the name, I didn't know its specific function. Then I went to read the official documentation, which clearly described its function, but did not tell us in what scenarios we need to use it. So I summarized some usage scenarios based on the description in the document, combined with the use of source code, and oriented to Google and stackoverflow. The role of cloneElementReact.cloneElement( element, [props], [...children] ) First, take a look at the official documentation of this API:
To sum up:
Usage scenariosAccording to the above definition, we can use this API as needed in different scenarios. Adding new props When we create a common component, we want to add different class names to each child element according to the internal logic. At this time, we can modify its Suppose we have a Timeline component that allows us to define multiple const MyTimeline = () => { return ( <Timeline> <TimelineItem>2020-06-01</TimelineItem> <TimelineItem>2020-06-08</TimelineItem> <TimelineItem>2020-07-05</TimelineItem> </Timeline> ) } // Inside the Timeline, the logic might be like this import class from 'classnames'; const Timeline = props => { // ... // ... const itemCount = React.children.count(props.children); const items = React.children.map(props.children, (item, index) => { return React.cloneElement(item, { className: class([ item.props.className, 'timeline-item', index === count - 1 ? 'timeline-item-last' : '' ]) }) } return <div className={'timeline'}>{ items }</div> } In addition to adding class Switch extends React.Component { render() { return ( <RouterContext.Consumer> {context => { invariant(context, "You should not use <Switch> outside a <Router>"); const location = this.props.location || context.location; let element, match; // We use React.Children.forEach instead of React.Children.toArray().find() // here because toArray adds keys to all child elements and we do not want // to trigger an unmount/remount for two <Route>s that render the same // component at different URLs. React.Children.forEach(this.props.children, child => { if (match == null && React.isValidElement(child)) { element = child; const path = child.props.path || child.props.from; match = path ? matchPath(location.pathname, { ...child.props, path }) : context.match; } }); return match React.cloneElement(element, { location, computedMatch: match }) : null; }} </RouterContext.Consumer> ); } } Events that modify props Suppose we have a Tab component, which contains multiple const Tab = props => { const { onClick } = props; const tabPanes = React.children.map(props.children, (tabPane, index) => { const paneClick = () => { onClick && onClick(index); tabPane.props?.onClick(); } return React.cloneElement(tabPane, { onClick: paneClick, }) }) return <div>{ tabPanes }</div> } Custom Style When creating a component called // For simplicity, mouse events are omitted here. const FollowMouse = props => { const { Content } = props; const customContent = React.isValidElement ? Content : <span>{ Content }</span> const getOffset = () => { return { position: 'absolute', top: ..., left: ..., } } const renderContent = React.cloneElement(custonContent, { style: { ...getOffset() } }) return <div>{ renderContent() }</div> } Add key When we create a list of elements, we can add a key to each node through const ComponentButton = props => { const { addonAfter, children } = props; const button = <button key='button'>{ children }</button> const list = [button, addonAfter ? React.cloneElement(addonAfter, { key: 'button-addon' } : null) return <div>{ list } <div> } Summarize When developing complex components, we often add different functions or display effects to child components as needed. The Of course, thanks to the powerful combination mode of react, this is not limited to The above is the detailed content of the detailed explanation of the use of React.cloneElement. For more information about the use of React.cloneElement, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: How to install nginx in docker and configure access via https
>>: Detailed explanation of binary and varbinary data types in MySQL
Table of contents background Solution 1 Ideas: Co...
Preface Nginx is an HTTP server designed for perf...
Method 1: Use the target event attribute of the E...
First, let’s take an example: There is a type fie...
500 (Internal Server Error) The server encountere...
Table of contents 1. JavaScript uses canvas in HT...
Let's make a simple 3D Rubik's Cube today...
Table of contents 1. What is a doubly linked list...
Table of contents Canal Maxwell Databus Alibaba C...
CSS: Copy code The code is as follows: *{margin:0;...
Upgrade process: Original system: CentOS7.3 [root...
For reference only for Python developers using Ub...
1. Introduction When the amount of data in the da...
Event bubbling, event capturing, and event delega...
Test project: react-demo Clone your react-demo pr...