【React】useRefを用いて値を取得しようとしたらundefinedと言われた。~備忘録~
3776 ワード
React HooksのuseRefを用いて、contenteditableにしたdivタグの値を取得するときに躓いたので備忘録として。
import React, { useRef } from 'react'
function InputWithDivTag() {
const refContainer = useRef('')
console.log(refContainer.current.value)
return (
<div
contentEditable="true"
ref={refContainer}
data-placeholder="入力してください"
/>
)
}
export default InputWithDivTag
いざ、値を入力してコンソールログの結果を見ると、、、
undefined
何でだろう。
めげません。頑張るのです。
とりあえず、
console.log(refContainer.current.value)
を
console.log(refContainer.current)
に変更しました。
すると、コンソールログの結果は
<div contenteditable="true" data-placeholder="入力してください">a</div>
refContainerが空っぽなわけではなさそうです。
考えます。
そもそも、参考にしたコードではcurrent.valueはinputタグに使われていた。
同じ入力でも、contenteditableによって入力可能となったdivタグとinputタグでは何かが違うのでは。
ググろう。
let me google it!
console.log(refContainer.current.innerText)
これで思ったように値を取得できました。
valueではなくinnerTextを使えば良かったのですね。
Author And Source
この問題について(【React】useRefを用いて値を取得しようとしたらundefinedと言われた。~備忘録~), 我々は、より多くの情報をここで見つけました https://qiita.com/haga2miya/items/32e4c7dd0e88781285bb著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .