ref returns undefined or null in react-ag捕鱼王app官网

current location:home > learning > web front-end > react >

ref returns undefined or null in react

author:jiyik last updated:2025/03/07 views:

react refs most often return undefined or null when we try to access their current properties before the corresponding dom element is rendered . to fix this, you need to access the ref in the useeffect hook or when an event is triggered.

import {useref, useeffect} from 'react';

export default functionapp() {
  const ref = useref();

  console.log(ref.current); // 👈️ undefined here

  useeffect(() => {
    const el2 = ref.current;
    console.log(el2); // 👈️ element here
  }, []);

  return (
    <div><divref={ref}><h2>helloh2>div>div>
  );
}

useref()the hook can be passed an initial value as an argument. the hook returns a mutable ref object whose .currentattributes are initialized to the passed argument.

we didn't pass an initial value to useref, so its current property is set to undefined.

if we pass null to the hook, its current property will be null if accessed immediately.

请注意, we have to access the current property of the ref object in order to access the div element on which we set the ref attribute.

when we pass a ref prop to an element, for example

, react sets the properties of the ref object .currentto the corresponding dom node.

we use useeffectthe hook because we want to make sure that the ref has been set on the element and that the element has been rendered to the dom.

if we try to access the current property of ref directly in the component, we'll get back undefined because ref hasn't been set yet and the div element hasn't been rendered yet.

we can also access the current properties of the ref in the event handler.

import {useref, useeffect} from 'react';

export default functionapp() {
  const ref = useref();

  console.log(ref.current); // 👈️ undefined here

  useeffect(() => {
    const el2 = ref.current;
    console.log(el2); // 👈️ element here
  }, []);

  const handleclick = () => {
    console.log(ref.current); // 👈️ element here
  };

  return (
    <div><divref={ref}><h2>helloh2>div><buttononclick={handleclick}>clickbutton>div>
  );
}

when the user clicks the button, the ref is already set and the corresponding element is rendered to the dom, so we can access it.


summarize

react refs most often return undefined or null when we try to access their current properties before the corresponding dom element is rendered . to fix this, useeffectaccess the ref in a hook or when an event is triggered.

for reprinting, please send an email to 1244347461@qq.com for approval. after obtaining the author's consent, kindly include the source as a link.

article url:

related articles

passing boolean values as props to components in react

publish date:2025/03/07 views:112 category:react

要将布尔值作为 props 传递给 react 中的组件,请将布尔值包裹在花括号中,例如 child bool={true} / 。 我们传递给组件的所有非字符串类型的道具都必须用大括号括起来。 function child ( {bo

using ref to get the height of an element in react

publish date:2025/03/07 views:195 category:react

在 react 中使用 ref 获取元素的高度: 初始化将存储元素高度的状态变量。 在 useeffect() 挂钩中更新元素的高度。 高度应设置为 ref.current.clientheight 。 import {useeffect, usestate, useref} from re

publish date:2025/03/07 views:133 category:react

在 react 中使用 ref 改变元素的样式: 在元素上设置 ref 属性。 通过 ref 上的 current 属性访问元素。 更新元素的样式,例如 ref.current.style.backgroundcolor = green 。 import {useref} from react ; cons

setting and accessing state with dynamic keys in react

publish date:2025/03/07 views:67 category:react

使用方括号表示法在 react 中使用动态键设置和访问状态,例如 setemployee({...employee, [key]: employee.salary 100}) 。 方括号中的变量或表达式将在设置状态之前进行评估。 import {usestate} from

add an event listener to the body element in react

publish date:2025/03/07 views:131 category:react

向 body 元素添加事件监听器: 访问文档对象上的 body 元素。 在 useeffect 钩子中对 body 元素使用 addeventlistener() 方法。 当组件卸载时移除事件侦听器。 import {useeffect} from react ; export defa

check if an element is in the viewport in react.js

publish date:2025/03/07 views:89 category:react

在 react.js 中检查元素是否在 viewport 中: 在元素上设置 ref 属性。 使用 intersectionobserver api 来跟踪元素是否相交。 app.js import {useeffect, useref, usestate, usememo} from react ; export default function

publish date:2025/03/07 views:161 category:react

要在 react 中按下 enter 键时获取输入的值: 在输入字段上设置 onkeydown 属性。 当用户按下一个键时,检查该键是否为 enter 。 从状态变量访问输入字段的值。 import {usestate} from react ; co

publish date:2025/03/06 views:154 category:react

要使用钩子清除 react 中的 timeout 或 interval: 使用 useeffect 钩子设置超时或间隔。 从 useeffect 钩子返回一个函数。 使用 cleartimeout() 或 clearinterval() 方法删除组件卸载时的超时。、 import

publish date:2025/03/06 views:113 category:react

在 react 中检查一个 prop 是否传递给了一个组件: 将 prop 与 undefined 进行比较。 如果 prop 等于 undefined ,则它不会传递给组件。 否则,它被传递给组件了。 const button = ( {withicon} ) = { if

scan to read all tech tutorials

social media
  • https://www.github.com/onmpw
  • qq:1244347461

recommended

tags

scan the code
easier access tutorial
网站地图