我的iframe組件中有一個元素,我需要以某種方式檢測該 iframe 的 URL 何時發生更改。到目前為止我嘗試過的:
- 添加了
onLoad回呼,但每次我在 iframe 中重定向時都不會觸發 - 使用過
React.useCallback但也不能像我想要的那樣作業 - 創建
timeout和iframe中獲取URL每一x秒
下面的簡約代碼示例
export const XComponent = (props: XComponentProps) => {
const ref = React.useRef<any>();
1.
const onLoad = () => {
const url = ref.current.contentWindow.location.href;
// do stg with url
}
2.
const getRef = React.useCallback((node: any) => {
// store node into state, this was not triggered properly either
}, []);
3.
React.useEffect(() => {
const interval = setInterval(() => {
const url = ref.current.contentWindow.location.href;
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div className={ styles.albertStoremanTab }>
<div className={ styles.container }>
<iframe id={"iframe-my-id"} onLoad={onLoad} src={props.defaultUrl} ref={ref}></iframe>
</div>
</div>
);
};
uj5u.com熱心網友回復:
這很簡單:
useEffect(() => {
// It runs only when defaultUrl changes
}, [props.defaultUrl])
uj5u.com熱心網友回復:
您是否嘗試在 useEffect 的依賴項陣列中使用 ref.current?
useEffect(() => { setURL(ref.current.contentWindow.location.href) }, [ref.current])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/347631.html
標籤:javascript 反应
