React.createElement() 方法: React.createElement() 方法用于创建元素。每当我们在 JSX 中编写代码时,JSX 都会将其转换为 React.createElement()。不推荐使用 createElement 方法,因为它很难维护或调试。我们每次都必须调用 React.createElement() 方法来创建 React 元素,即使它只是一个没有属性的 span 标签。
句法:
React.createElement(
type,
[props],
[...children]
)
示例:在这个示例中,我们使用 React.createElement() 方法创建了一个 div 元素。
App.js
import React from 'react';
import "./styles.css";
const title = React.createElement('h1',
{className:'title'}, 'GeeksforGeeks');
const App =()=>
React.createElement('div', {}, [
React.createElement('button',{className:'btn'}, title),
React.createElement('button', {className:'btn'}, title),
]);
export default App;
App.js
import React from 'react';
import Button from './Button';
import './styles.css';
const App = () => {
return (
)
}
const Parent = (props) => {
let btn = 'GeeksforGeeks';
return (
{React.Children.map(props.children,
child => {
return React.cloneElement(child,
{ btn }, null);
// third parameter is null
// Because we are not adding
// any children
})}
)
}
export default App;
Button.js
import React from 'react';
const Button=(props)=> {
return (
)
}
export default Button;
输出:
React.cloneElement() 方法:当父组件想要添加或修改其子组件的 props 时,会使用 React.cloneElement() 方法。 React.cloneElement()函数创建一个给定元素的副本,我们也可以将 props 和 children 传递给函数。
句法:
React.cloneElement(
element,
[props],
[...children]
)
例子:在这个例子中,我们使用了 cloneElement 来传递 props。
应用程序.js
import React from 'react';
import Button from './Button';
import './styles.css';
const App = () => {
return (
)
}
const Parent = (props) => {
let btn = 'GeeksforGeeks';
return (
{React.Children.map(props.children,
child => {
return React.cloneElement(child,
{ btn }, null);
// third parameter is null
// Because we are not adding
// any children
})}
)
}
export default App;
按钮.js
import React from 'react';
const Button=(props)=> {
return (
)
}
export default Button;
输出:
createElement | cloneElement |
---|---|
createElement is the code that JSX gets compiled or converted into and is used by reacting to create elements. | cloneElement is used for cloning elements and passing them new props. |
This method is used to describe how the User Interface looks. | This method is used to manipulate the elements. |
createElement requires type, props, and children as arguments. | cloneElement requires elements, props, and children as arguments. |
It creates and returns a new element with the type as given in the arguments. | It clones and returns a new element with the properties of a given element. |