当用户使用 React 和 Typescript 位于“/items/:itemId”页面时,我想将正确的属性从 16px 更改为 40px。
下面是我的组件片段,
const root = () => {
<PopupContextProvider>
<App/>
</PopupContextProvider>
}
export const PopupContextProvider = ({ children }: any) => {
return (
<popupContext.Provider value={context}>
{children}
{(condition1 || condition2) && (
<Popup onHide={dismiss} />
)}
</popupContext.Provider>
);
}
export function Popup({ onHide }: Props) {
return (
<Dialog>
<DialogBody>
<span>Title</span>
<Description/>
</DialogBody>
<Actions>
<span>Hide</span>
</Actions>
</Dialog>
);
}
const Dialog = styled.div`
position: fixed;
right: 16px;//want to change this to 40px if user is in page
"/items/:itemId"
display: flex;
flex-direction: column;
`;
我尝试过什么?
export function Popup({ onHide }: Props) {
const location = useLocation();
const [isView, setIsView] = React.useState(false);
if (location.pathname === '/items/:itemId') {
setIsView(true);
//Here, it doesn't change to true.
//How can I do the same in useEffect or something that updates
}
return (
<Dialog isView={isView}>
<DialogBody>
<span>Title</span>
<Description/>
</DialogBody>
<Actions>
<span>Hide</span>
</Actions>
</Dialog>
);
}
const Dialog = styled.div<isView?:boolean>`
position: fixed;
${({ isView }) => isView && 'right: 40px;'}
display: flex;
flex-direction: column;
`;
即使用户在页面“/items/:itemId”中,我上面的代码也不会用正确的 40px 更新弹出窗口的位置。
我不确定出了什么问题。有人可以帮我弄这个吗?谢谢。
编辑:
我根据提供的答案之一进行了尝试。
export function Popup({ onHide }: Props) {
const location = useLocation();
const [isView, setIsView] = React.useState(false);
React.useEffect(() => {
const match = matchPath(
location.pathname,
'/items/:itemId'
);
if (match) { //it doesnt get it into this condition since match is
//null
setIsScheduleView(true);
}
}, []);
return (
<Dialog isView={isView}>
<DialogBody>
<span>Title</span>
<Description/>
</DialogBody>
<Actions>
<span>Hide</span>
</Actions>
</Dialog>
);
}