创建一个组件并再父组件中调用,要用通过属性来控制子组件的显示状态
时间: 2023-11-18 12:02:26 浏览: 19
好的,以下是一个简单的示例代码:
子组件 ChildComponent:
```jsx
import React from "react";
const ChildComponent = ({ show }) => {
return (
<div style={{ display: show ? "block" : "none" }}>
<h2>我是子组件</h2>
</div>
);
};
export default ChildComponent;
```
在父组件中引入并调用子组件:
```jsx
import React, { useState } from "react";
import ChildComponent from "./ChildComponent";
const ParentComponent = () => {
const [showChild, setShowChild] = useState(false);
const handleClick = () => {
setShowChild(!showChild);
};
return (
<div>
<button onClick={handleClick}>{showChild ? "隐藏" : "显示"}子组件</button>
<ChildComponent show={showChild} />
</div>
);
};
export default ParentComponent;
```
在父组件中使用 `useState` 来管理子组件的显示状态。通过 `handleClick` 函数来控制显示/隐藏子组件,并通过 `show` 属性将状态传递给子组件,子组件根据 `show` 属性的值来显示/隐藏自己。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)