Created
May 9, 2019 14:52
-
-
Save Nkzn/5fd1badf50b3044fe797ea7e703b40be to your computer and use it in GitHub Desktop.
コンポーネントがDOMツリーに書き込まれたタイミングで、Reactの外側にコールバックを実行するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
export default class ClassComponent extends React.Component { | |
componentDidMount() { | |
if (this.ref) { | |
const event = new CustomEvent('initializedWithClassComponent', { detail: this.ref }); | |
window.dispatchEvent(event); | |
} | |
} | |
render() { | |
return ( | |
<div className="class-div" ref={ref => this.ref = ref}> | |
This is class component. | |
</div> | |
) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useRef, useEffect } from 'react'; | |
export default () => { | |
const divRef = useRef(null); | |
useEffect(() => { | |
if (divRef.current) { | |
const event = new CustomEvent('initializedWithHooksComponent', { detail: divRef.current }); | |
window.dispatchEvent(event); | |
} | |
}); | |
return ( | |
<div className="hooks-div" ref={divRef}> | |
This is hooks component. | |
</div> | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<script> | |
window.addEventListener('initializedWithClassComponent', (e) => { | |
console.log('initializedWithClassComponent', { detail: e.detail }); | |
// このタイミングでquerySelectorしてもOK | |
const classDiv = document.querySelector('div.class-div'); | |
console.log('initializedWithClassComponent', { classDiv }); // classDivの中身はe.detailと同じ | |
}, false); | |
window.addEventListener('initializedWithHooksComponent', (e) => { | |
console.log('initialized(or updated)WithHooksComponent', { detail: e.detail }); | |
// このタイミングでquerySelectorしてもOK | |
const hooksDiv = document.querySelector('div.hooks-div'); | |
console.log('initialized(or updated)WithHooksComponent', { hooksDiv }); // hooksDivの中身はe.detailと同じ | |
}, false); | |
</script> | |
</head> | |
<body> | |
<div id="root"></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment