preface The React.cloneElement method is encountered from time to time, and I read the official website documents many times, but I still have little knowledge of how to use it. Therefore, I go deep into the source code layer to find a calling solution. This article will analyze and summarize the usage of React.cloneElement from the source code layer version react source code version: 16.6.1 body usage Clone with element element as template and return new React element. You can modify props, key, ref through config parameter, and child element through children. Any parameter can be passed in React.cloneElement, and will be used as a child element of the new React element starting from the third parameter example import React from "react"; import "./style.css"; export default function App() { const Clone = React.cloneElement(<Temp/>, {key: 123, name: "Zhang San"}, <div>Hello, World 1.</div>, <div>Hello, World 2.</div>) return ( <div> {Clone} </div> ); } const Temp = (props) => { return ( <div> <span>Hello world, {props.name}</span> {props.children} </div> ) }; // Page output Hello world, Zhang San Hello, World.1 Hello, World.2 Parameter analysis element elements of react config object parameter, which can contain the following properties ref: not required to replace ref in the original element key: not required to replace key in the original element other attributes: all props as new element children The child element parameter is more appropriate here. Children parse declare that props, key, ref, self, source, owner are assigned default values based on element const props = Object.assign({}, element.props); // Reserved names are extracted let key = element.key;…

May 24, 2023 0comments 1348hotness 0likes Aaron Read all