简体   繁体   中英

How can I access data attribute value using useRef hook?

I can access value of className and id by using boardRef.current.className and boardRef.current.id, but if I use boardRef.current.data-board then I get "cannot read properties of undefined". Is there any way to access data attribute using useRef hook?

import React, {useState, useRef} from 'react';

export default function App() {
  const boardRef = useRef();

  const getData = () => {
    console.log(boardRef.current.data-board);
  }
  getData();

  return (
    <div className="App">
      <h1>Tic Tac Toe</h1>
      <div ref={boardRef} className="board" id="boardOne" data-board="one"></div>
    </div>
  );
}

Using React#useEffect and Element#getAttribute :

const getData = () => {
  console.log(boardRef.current.getAttribute("data-board"));
};

React.useEffect(() => {
  getData();
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM