通过子组件在父组件中反应切换视图功能
Posted
技术标签:
【中文标题】通过子组件在父组件中反应切换视图功能【英文标题】:React toggle view functionality in the parent via child component 【发布时间】:2021-07-17 05:52:22 【问题描述】:我正在尝试在膳食列表和膳食详细信息之间切换视图。我在 Meals.js 的子组件 Meal.js 中放置了一个按钮,该按钮是列表和详细信息视图。
你能帮我解决这个问题吗?即使使用我在下面的代码中使用的条件渲染方法,它似乎也无法正常工作。
Meal.js
import useState from 'react'
import './Meal.css'
const Meal = (props) =>
const [isToggled, setIsToggled] = useState(false);
const sendIdHandler = () =>
if (isToggled === true)
setIsToggled(false);
else
setIsToggled(true);
props.onSaveIdHandler(props.id, isToggled)
return (
<div
className='meal'
onClick=sendIdHandler
>
props.label
</div>
);
export default Meal;
Meals.js
import Meal from './Meal/Meal'
const Meals = (props) =>
let toggleCondition = false;
const saveIdHandler = (data, isToggled) =>
toggleCondition = isToggled;
const mealDetails = props.mealsMenuData.findIndex(i =>
i.id === data
)
console.log(mealDetails, toggleCondition)
return (
<div>
toggleCondition === false &&
props.mealsMenuData.map(item =>
<Meal
key=item.id
id=item.id
label=item.label
onSaveIdHandler=saveIdHandler
/>
)
toggleCondition === true &&
<div>Horray!</div>
</div>
);
export default Meals;
更新
终于想出了如何正确地做到这一点。我将条件 true/false useState 放在父级中,并让 Meal.js 仅发送查看项目所需的 id
代码如下..
Meals.js
import useState from 'react'
import Meal from './Meal/Meal'
import MealDetails from './MealDetails/MealDetails'
const Meals = (props) =>
const [show, setShow] = useState(false);
const [mealId, setMealId] = useState(0);
const saveIdHandler = (data) =>
setShow(true);
setMealId(props.mealsMenuData.findIndex(i =>
i.id === data)
)
console.log(props.mealsMenuData[mealId].ingridients)
const backHandler = () =>
setShow(false)
return (
<div>
show === false &&
props.mealsMenuData.map(item =>
<Meal
key=item.id
id=item.id
label=item.label
onSaveIdHandler=saveIdHandler
/>
)
show === true &&
<div>
<MealDetails data=props.mealsMenuData[mealId] />
<button onClick=backHandler>Back</button>
</div>
</div>
);
export default Meals;
Meal.js
import './Meal.css'
const Meal = (props) =>
const sendIdHandler = () =>
props.onSaveIdHandler(props.id)
return (
<div
className='meal'
onClick=sendIdHandler
>
props.label
</div>
);
export default Meal;
【问题讨论】:
【参考方案1】:你在sendIdHandler
的问题:你可以这样更新:
const sendIdHandler = () =>
const newIsToggled = !isToggled;
setIsToggled(newIsToggled)
props.onSaveIdHandler(props.id, newIsToggled)
【讨论】:
以上是关于通过子组件在父组件中反应切换视图功能的主要内容,如果未能解决你的问题,请参考以下文章
使用 forwardRef 反应总是更新子组件,即使使用备忘录
react/flux- 子组件用户事件 - 一切都应该通过调度程序路由吗