在React中,可以创建自定义组件来构建可重用的UI元素。有两种方式可以创建自定义组件:函数组件和类组件。
函数组件是一种简单的方式,它接收一个props对象作为参数,并返回一个React元素。以下是一个创建函数组件的示例
import React from 'react';
function CustomComponent(props) { return (
{props.title}
{props.content}
export default CustomComponent; 在上面的例子中,我们定义了一个名为CustomComponent的函数组件,它接收props作为参数并返回一个包含标题和内容的
类组件是使用ES6类语法创建的组件,它继承自React.Component基类,并通过重写render()方法来定义组件的UI。以下是一个创建类组件的示例:
import React from 'react';
class CustomComponent extends React.Component { render() { return (
{this.props.title}
{this.props.content}
export default CustomComponent; 在上面的例子中,我们定义了一个名为CustomComponent的类组件,并在render()方法中返回包含标题和内容的
使用这些自定义组件时,你可以像使用内置HTML元素一样使用它们。例如:
import React from 'react'; import CustomComponent from './CustomComponent';
function App() { return (
My App
export default App;
在上面的例子中,我们在App组件中使用了自定义的CustomComponent,并通过props传递了标题和内容。
无论是函数组件还是类组件,它们都可以在应用程序中被重用,并且可以在不同的上下文中使用。你可以根据自己的需求选择适合的方式来创建自定义组件。