Slide 1

Slide 1 text

useRefʹ͍ͭͯௐ΂ͯΈͨ @shibe97 2019.9.4 React LTձ

Slide 2

Slide 2 text

ࣲా ࿨ف ΢ΥϯλגࣜձࣾͰmicroCMSͱ͍͏ϔουϨεCMSΛ ࡞͍ͬͯ·͢ɻ ීஈ͸React࢖͍Ͱɺ࠷ۙVue΋ͪΐͬͱ৮Γ·͢ɻ @shibe97

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

ೖྗϑΥʔϜͱAPIΛඵͰ࡞੒Ͱ͖ΔαʔϏε

Slide 5

Slide 5 text

React Hooksͱ͸ • React 16.8͔Β௥Ճ͞Εͨػೳ • Functional ComponentʹClass Componentͱಉ༷ͷॲཧ͕
 Ͱ͖ΔΑ͏ʹ௥Ճ͞Εͨ • state΍ϥΠϑαΠΫϧ૬౰ͷ΋ͷ

Slide 6

Slide 6 text

useRefͱ͸ • DOMͷࢀরʹ࢖͑Δ • ࠶ඳըͤ͞ͳ͍ม਺؅ཧ͕Ͱ͖Δ

Slide 7

Slide 7 text

DOMͷࢀরʹ࢖͑ΔʢެࣜྫΑΓʣ function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` points to the mounted text input element inputEl.current.focus(); }; return ( <> Focus the input > ); }

Slide 8

Slide 8 text

࠶ඳըͤ͞ͳ͍ม਺؅ཧ͕Ͱ͖Δ • refΦϒδΣΫτ͸஋ΛcurrentϓϩύςΟʹอ࣋͢Δ • ࠶ඳը࣌΋ɺຖճಉ͡refΦϒδΣΫτΛฦ͢ • currentʹ௚઀୅ೖͯ͠΋࠶ඳը͸͞Εͳ͍ { current: initialValue }

Slide 9

Slide 9 text

useRefͷ࣮૷ function mountRef(initialValue: T): {current: T} { const hook = mountWorkInProgressHook(); const ref = {current: initialValue}; if (__DEV__) { Object.seal(ref); } hook.memoizedState = ref; return ref; } function updateRef(initialValue: T): {current: T} { const hook = updateWorkInProgressHook(); return hook.memoizedState; } ϝϞϦ্ͷ஋Λຖճฦ͚ͩ͢ ϝϞϦ্ͰΦϒδΣΫτΛอ࣋ currentϓϩύςΟʹ஋Λอ࣋

Slide 10

Slide 10 text

͜ͷ࢓૊ΈΛར༻Ͱ͖ΔྫͬͯͳΜͩΖ͏

Slide 11

Slide 11 text

DOMͩʂ

Slide 12

Slide 12 text

inputཁૉͷྫ: useState function TextInput() { const [ text, setText ] = useState(‘’); const onChange = useCallback(e => { setText(e.target.value); }; return ( ); } ςΩετΛมߋ͢Δͨͼʹඳը͞ΕΔ

Slide 13

Slide 13 text

inputཁૉͷྫ: useRefʢcurrent௚ࢦఆʣ function TextInput() { const { current } = useRef(null); const onChange = useCallback(e => { current = e.target.value; }); return ( ); } ςΩετΛมߋͯ͠΋࠶ඳը͞Εͳ͍

Slide 14

Slide 14 text

͋ΕɺͰ΋͜Εͬͯɾɾɾ

Slide 15

Slide 15 text

inputཁૉͷྫ: useRefʢDOMࢀরʣ function TextInput() { const inputEl = useRef(null); return ( ); } ΋ͪΖΜ͜ͷํ๏΋࠶ඳը͞Εͳ͍

Slide 16

Slide 16 text

·ͱΊ • useRef͸஋Λอ࣋Ͱ͖Δ্ʹɺมߋͯ͠΋࠶ඳը͞Εͳ͍ • inputཁૉʹ͸useStateΑΓuseRefͷํ͕ύϑΥʔϚϯε͸ྑ͍ • ΋ͪΖΜControlled Componentʹ͍ͨ͠৔߹͸useStateʹ͢Δ ඞཁ͋Γ

Slide 17

Slide 17 text

͓·͚

Slide 18

Slide 18 text

useRef͸ΦϒδΣΫτΛࢀর͍ͯ͠Δ͔Β ಺෦ϓϩύςΟมߋͨ͠ͱ͜ΖͰ࠶ඳը͞Εͳ͍ΜͩΖ͏

Slide 19

Slide 19 text

Α͠ɺLTωλ͸͜ΕͰ͍͜͏ʂ

Slide 20

Slide 20 text

useRefͷ࣮૷ function mountRef(initialValue: T): {current: T} { const hook = mountWorkInProgressHook(); const ref = {current: initialValue}; if (__DEV__) { Object.seal(ref); } hook.memoizedState = ref; return ref; } function updateRef(initialValue: T): {current: T} { const hook = updateWorkInProgressHook(); return hook.memoizedState; } ϝϞϦ্ͷ஋Λຖճฦ͚ͩ͢ ϝϞϦ্ͰΦϒδΣΫτΛอ࣋ currentϓϩύςΟʹ஋Λอ࣋

Slide 21

Slide 21 text

·ͬͨؔ͘܎ͳ͔ͬͨ

Slide 22

Slide 22 text

Thanks :) @shibe97