react 根据 子组件 传来的布尔值条件渲染另外两个子组件
时间: 2023-08-18 21:36:22 浏览: 46
可以使用条件渲染语句(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`。
相关问题
父组件传给子组件一个布尔值和一个对象
好的,父组件传给子组件一个布尔值和一个对象,可以通过props来实现。在父组件中定义一个布尔值和一个对象,然后将它们作为props传递给子组件即可。具体代码如下:
```jsx
// 父组件
import React from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const boolValue = true;
const objValue = { name: 'Tom', age: 18 };
return (
<div>
<ChildComponent boolProp={boolValue} objProp={objValue} />
</div>
);
}
export default ParentComponent;
// 子组件
import React from 'react';
function ChildComponent(props) {
const { boolProp, objProp } = props;
return (
<div>
<p>布尔值:{boolProp.toString()}</p>
<p>对象:{JSON.stringify(objProp)}</p>
</div>
);
}
export default ChildComponent;
```
在子组件中,通过props获取父组件传递过来的布尔值和对象,并在页面上展示出来。
react 子组件点击按钮向父组件传递一个布尔值
可以通过在子组件中定义一个函数,然后将该函数作为props传递给子组件,在子组件中调用该函数并传递布尔值作为参数,从而实现向父组件传递布尔值的功能。具体实现如下:
在子组件中定义一个函数 handleClick,该函数接收一个布尔值作为参数,并调用props中传递的函数 onButtonClick:
```
import React from "react";
function ChildComponent(props) {
const handleClick = (boolValue) => {
props.onButtonClick(boolValue);
};
return (
<div>
<button onClick={() => handleClick(true)}>True</button>
<button onClick={() => handleClick(false)}>False</button>
</div>
);
}
export default ChildComponent;
```
在父组件中定义一个函数 handleButtonClick,该函数接收子组件传递的布尔值作为参数,并更新父组件的状态:
```
import React, { useState } from "react";
import ChildComponent from "./ChildComponent";
function ParentComponent() {
const [value, setValue] = useState(null);
const handleButtonClick = (boolValue) => {
setValue(boolValue);
};
return (
<div>
<ChildComponent onButtonClick={handleButtonClick} />
{value !== null && (
<p>You clicked {value ? "True" : "False"}</p>
)}
</div>
);
}
export default ParentComponent;
```
在父组件中渲染子组件,并将 handleButtonClick 函数作为 props 传递给子组件。当子组件中的按钮被点击时,会调用 handleClick 函数,该函数会调用传递给子组件的 onButtonClick 函数,并将布尔值作为参数传递给该函数。此时,父组件中的 handleButtonClick 函数会被调用,并且更新父组件的状态。最后,父组件根据状态的值来渲染相应的内容。