react 根据 子组件 传来的布尔值条件渲染另外两个子组件
时间: 2023-08-18 21:36:22 浏览: 97
可以使用条件渲染语句(Conditional Rendering)来根据子组件传来的布尔值来渲染另外两个子组件。具体实现可以采用下面的代码:
```javascript
function ParentComponent() {
const [showComponentA, setShowComponentA] = useState(false);
const handleToggleComponentA = () => {
setShowComponentA(!showComponentA);
};
return (
<div>
<button onClick={handleToggleComponentA}>Toggle Component A</button>
{showComponentA ? <ComponentA /> : <ComponentB />}
</div>
);
}
```
在这个例子中,我们使用了一个布尔值 `showComponentA` 来控制要渲染的子组件。当用户点击按钮时,`handleToggleComponentA` 函数会将 `showComponentA` 的值取反,达到切换显示两个子组件的效果。然后,我们使用条件渲染语句 `showComponentA ? <ComponentA /> : <ComponentB />` 来渲染要显示的子组件,如果 `showComponentA` 为真,则渲染 `ComponentA`,否则渲染 `ComponentB`。
阅读全文
相关推荐









