[英]React conditionally render component using an outside function
I'm working on a modal function in an application.我正在应用程序中处理模态 function。 Since the app has different modals, I have a function which handles the open & close state of various windows:
由于应用程序有不同的模式,我有一个 function 处理各种 windows 的打开和关闭 state:
const OpenItem = ({ toggle, content }) => {
const [isShown, setIsShown] = useState(false);
const hide = () => setIsShown(false);
const show = () => setIsShown(true);
return (
<>
{toggle(show)}
{isShown && content(hide)}
</>
);
};
export default OpenItem;
Now in my main component, I want to to use this function with another component:现在在我的主要组件中,我想将此 function 与另一个组件一起使用:
const Header = () => {
return (
<div>
<OpenItem
toggle={(show) => <Button onClick={show}>icon</Button>}
content={(hide) => (
// Component to hide:
<ComponentToShowOrHide onClick={hide} />
)}
/>
</div>
);
};
export default Header;
This works fine, except that instead of having the {hide}
function as a part of the imported component, I want to toggle the view in <Button onClick={show}>icon</Button>
这工作正常,除了将
{hide}
function 作为导入组件的一部分,我想在<Button onClick={show}>icon</Button>
中切换视图
My idea is to conditionally render the show or hide in the button instead of rendering it in the component, but I'm not quite sure how to do that since I haven't used an outside function to control a function in a component.我的想法是有条件地在按钮中渲染显示或隐藏,而不是在组件中渲染它,但我不太确定如何做到这一点,因为我没有使用外部 function 来控制组件中的 function。
Simply write a function that toggles the state rather than sets it to a value.只需编写一个 function 来切换 state 而不是将其设置为一个值。
const OpenItem = ({ toggle, content }) => {
const [isShown, setIsShown] = useState(false);
return (
<>
{toggle(() => setIsShown(prevState => !prevState))}
</>
);
};
export default OpenItem;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.