简体   繁体   English

如何使用 useRef 钩子访问数据属性值?

[英]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".我可以通过使用 boardRef.current.className 和 boardRef.current.id 来访问 className 和 id 的值,但是如果我使用 boardRef.current.data-board 那么我会得到“无法读取未定义的属性”。 Is there any way to access data attribute using useRef hook?有没有办法使用 useRef 钩子访问数据属性?

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 :使用React#useEffectElement#getAttribute

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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