react如何调用组件
调用 React 组件的方法
在 React 中调用组件主要分为两种方式:函数组件和类组件。以下是具体的实现方法。
函数组件的调用
函数组件是简单的 JavaScript 函数,直接通过函数名调用即可。
function Greeting() {
return <h1>Hello, World!</h1>;
}
// 在其他组件中调用
function App() {
return (
<div>
<Greeting />
</div>
);
}
类组件的调用
类组件继承自 React.Component,通过类名调用。

class Greeting extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
// 在其他组件中调用
class App extends React.Component {
render() {
return (
<div>
<Greeting />
</div>
);
}
}
传递 Props
组件可以通过 Props 接收数据。
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
// 调用时传递 Props
function App() {
return (
<div>
<Greeting name="Alice" />
</div>
);
}
动态渲染组件
可以通过条件判断动态渲染组件。

function AdminPanel() {
return <div>Admin Panel</div>;
}
function UserPanel() {
return <div>User Panel</div>;
}
function App({ isAdmin }) {
return (
<div>
{isAdmin ? <AdminPanel /> : <UserPanel />}
</div>
);
}
组件组合
多个组件可以组合在一起使用。
function Header() {
return <header>Header</header>;
}
function Footer() {
return <footer>Footer</footer>;
}
function App() {
return (
<div>
<Header />
<main>Content</main>
<Footer />
</div>
);
}
使用 Children
组件可以通过 props.children 接收子元素。
function Card(props) {
return <div className="card">{props.children}</div>;
}
function App() {
return (
<Card>
<h2>Title</h2>
<p>Content</p>
</Card>
);
}
以上方法涵盖了 React 中调用组件的常见场景,根据需求选择合适的方式即可。






