标签: use-ref

这是检测反应组件中第一次渲染的正确方法

我有一个场景,我需要检测组件的第一次渲染。我在这里构建了一个小例子。有人可以向我解释什么是正确的方法吗?

为什么大多数人建议使用 aref而不是普通状态。

https://codesandbox.io/s/condescending-burnell-0ex3x?file=/src/App.js

import React, { useState, useRef, useEffect } from "react";
import "./styles.css";

export default function App() {
  const firstRender = useDetectFirstRender();
  const [random, setRandom] = useState("123");
  useEffect(() => {
    if (firstRender) {
      console.log("first");
    } else {
      console.log("second");
    }
  }, [random]);
  return (
    <div className="App">
      <h1>Random Number is {random}</h1>
      <button onClick={() => setRandom(Math.random())}>Change Name</button>
    </div>
  );
}

//Approach 1
// export function useDetectFirstRender() {
//   const firstRender = useRef(true);

//   useEffect(() => {
//     firstRender.current = …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks use-ref

22
推荐指数
4
解决办法
4万
查看次数

无法在 React useRef 中分配给只读属性“current”

useRef在功能组件中使用了 React 来获取 html 对象上的链接并将其存储在 Recoilatom 中。例如:

const Children = () => {
  const [refLink, setSrefLink] = useRecoilState(refLink)
  return <input ref={someRef}/>
}
const Parent = () => {
  const [refLink, setSrefLink] = useRecoilState(refLink)
  const someRef = useRef();
  setSomeRef(someRef)
  return <Children />;
}

export const refLink = atom({
    key: 'refLink',
    default: null ,
});
Run Code Online (Sandbox Code Playgroud)

但是当我的父组件卸载时我收到错误:

react-dom.development.js:20997未捕获类型错误:无法分配给文件reac-dom.development.js中对象“#”的只读属性“当前”

在此输入图像描述

我无法想象有什么问题;

javascript reactjs use-ref recoiljs

22
推荐指数
2
解决办法
1万
查看次数

React:在第二个容器中插入(渲染)时如何等待 ref 可用

编辑:更好的解释

上下文:

我从第三台服务器收到一些纯 HTML 代码,我想要

  • 插入我的 React 应用程序
  • 修改它

普通的 JS 方法

  • 我可以使用正则表达式修改字符串并添加任何带有id
  • 然后我可以getElementById像往常一样通过 修改这些元素

React 方法

  • 我不应该使用 DOM
  • 然后我应该在字符串中插入一些内部有 React ref 的组件
  • 相反(以纯 HTML 形式插入一些 React 组件)将通过ReactDOMServer.renderToString
  • 因此,当我使用 注入组件时ReactDOM.render(),问题是该render方法需要时间,因此,如果在下一行中我尝试使用插入组件中存在的引用,但该引用尚未存在

问题

  • 怎么做?通常我会将代码放在useEffect带有[]依赖项的 a 中,但这里我是rendering应用程序已安装时的组件
  • 一个快速的解决方法是只进行 500 毫秒的异步等待,然后我可以访问ref,但肯定有更好的东西

此代码失败,因为当ref呈现时它仍然不可用,因此ref.current未定义

我该如何等待呢?

代码沙盒

编辑:我提供了有效的代码,但通过直接 DOM,我认为应该避免这种情况

import React, { useRef, useEffect } from "react";
import ReactDOM from "react-dom";

export default function App() {
  const …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks use-effect use-ref

12
推荐指数
2
解决办法
2万
查看次数

如何在组件中使用 React.forwardRef() 和自己的 ref ?


我正在尝试使用React.forwardRef()并同时React.useRef()在组件中使用的任务。

问题我只能
使用使用forwardRef 属性。所以,我不知道如何一起使用它们。示例代码:myOwnRef ref

interface IExampleInputProps {
    value: string,
    onChange: (event: ChangeEvent<HTMLInputElement>) => void
}
const ExampleInput = forwardRef<HTMLInputElement | null, IExampleInputProps>(({value, onChange}, ref) => { // can't to use "ref" parameter
    const myOwnRef = React.useRef<HTMLInputElement | null>(null);

    return <input ref={el => {
        myOwnRef.current = el; // => OK
        if (ref) { // trying to use the ref passed from the forwardRef function
            ref.current = el; // => ERROR
        } …
Run Code Online (Sandbox Code Playgroud)

reactjs react-forwardref use-ref

12
推荐指数
1
解决办法
5371
查看次数

useRef() 钩住自定义组件

我正在尝试创建一个导航栏,当用户单击其中一个链接时,页面会滚动到某个部分。在上面的代码中,每个元素都是我页面的一部分:

    <Navbar scrollFunc={scrollToRef} />      
    <Mainlogo ref={mainLogoRef} />
    <Sales  ref={salesRef} />
    <Introduction ref={introductionRef} />
    <Blog ref={blogRef} />
    <Footer />

Run Code Online (Sandbox Code Playgroud)

'refs' 被声明如下,使用 useRef 钩子:

  const mainLogoRef = useRef(null)
  const salesRef = useRef(null)
  const introductionRef = useRef(null)
  const blogRef = useRef(null)

Run Code Online (Sandbox Code Playgroud)

我用来滚动的功能如下:

  const scrollToRef = ref => {
    window.scrollTo({ top: ref.current.offsetTop, behavior: "smooth" })
  }

Run Code Online (Sandbox Code Playgroud)

问题是“当前”键始终未定义。当我做这样的事情时:

<div ref={salesRef}> <Sales  /><div>

Run Code Online (Sandbox Code Playgroud)

或者

<section ref={salesRef}> <Sales  /><section>

Run Code Online (Sandbox Code Playgroud)

一切正常。我假设 'ref' 仅适用于 html 'pure' 标签。有没有办法在自定义组件中使用“useRef”钩子?

免责声明:对不起,英语不好,我不是母语人士。

javascript reactjs react-hooks use-ref

9
推荐指数
1
解决办法
9096
查看次数

React - 使用 useRef 触发表单提交

美好的一天,所以我试图在表单操作=“POST”发生之前执行中间功能。我首先尝试了两件事 onSubmit={functionName} 但表单始终执行该操作,即使在 onSubmit 函数中我返回 false。其次,我一直在尝试使用 useRef 来以编程方式分派提交事件,但没有任何反应?我本质上必须进行服务器端调用来获取发布的表单值的配置,不幸的是我使用的外部 API 需要以这种方式提交表单。请提供任何帮助,我们将不胜感激。

尝试1:

const performSubmit =() => {
 //Using onSubmit and then only performing the return after the axios call is done
 axiosCallFunction.then((res) => {
   setConfig(res.data)
   return true
 }).catch((error)) => {
   //Dont submit form
   return false
 })
}

return (
<form name="form" onSubmit={performSubmit} id="x1" method="POST" action="https://url.aspx" target="_top">
    <input value={config.param}/>
    <button type="submit"> Submit</button>
</form>)

Run Code Online (Sandbox Code Playgroud)

尝试2

const formEl = useRef();

const performSubmit =() => {
 //Currently not calling the submit on the form
 formEl.current.dispatchEvent(new …
Run Code Online (Sandbox Code Playgroud)

forms onsubmit reactjs react-hooks use-ref

9
推荐指数
2
解决办法
2万
查看次数

useRef 来存储之前的状态值

我对下面使用 useRef 存储以前的状态值感到困惑。本质上,它如何能够正确显示先前的值。由于 useEffect 依赖于“value”,我的理解是每次“value”更改(即当用户更新文本框时),它会将“prevValue.current”更新为新输入的值。

但这似乎不是正在发生的事情。在这种情况下,步骤的顺序是什么?

function App() {
  const [value, setValue] =  useState("");
  const prevValue = useRef('')
  useEffect(() => {
    prevValue.current = value;
  }, [value]);
  return (
    <div>
      <input
        value={value}
        onChange={e => setValue(e.target.value)}
      />
      <div>
        Curr Value: {value}
      </div>
      <div>
        Prev Value: {prevValue.current}
      </div>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks use-ref

7
推荐指数
1
解决办法
1423
查看次数

useRef 抛出无法分配给类型 LegacyRef&lt;Slider&gt; | 不明确的

我正在使用react-slick-slider,我想要实现的是制作自定义箭头。
所以代码看起来像这样:

const FeedbackSlider = () => {
const [isLargeScreen] = useMediaQuery("(min-width: 1050px)")

const sliderRef = useRef<Slider>()

const prev = () => {
    sliderRef.current?.slickPrev()
}
const next = () => {
    sliderRef.current?.slickNext()
}
const settings = {
    dots: false,
    infinite: true,
    speed: 500,
    slidesToShow: (isLargeScreen ? 2 : 1),
    slidesToScroll: 1,
    prevArrow: (isLargeScreen && <PrevArrow />),
    nextArrow: (isLargeScreen && <NextArrow />)
};
return (
    <Box px={['2', '4', '8', '16']} mx='auto' pt='12'>
        <Slider ref={sliderRef} {...settings}>
           // slider cards...
        </Slider>
        {!isLargeScreen && …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs react-slick use-ref

7
推荐指数
1
解决办法
1万
查看次数

避免子组件更新父状态时父组件重新渲染,

在我们的反应应用程序中,我们有父子组件。子组件调用父方法来更新父状态值。这是示例代码

//父组件

const parent = ({ items }) => {
    const [information, setInformation] = useState([]);
    const updateParentInformation = (childUpdate) => {
         setInformation(information + childUpdates)
    }
    return (
        <div>
            <div>{information}</div>
            ...
            {items.map((item) => {
                return (
                    <ChildComponent item={item} updateParentInformation={updateParentInformation} />
            )})}
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

//子组件

const ChildComponent = ({ item, updateParentInformation }) => {
    useEffect(() => {
        const cardInformation = calculateCardInformation(item)
        updateParentInformation(cardAmpScripts)
     }, [item])
    return (
        <div>
            .....
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

因此子组件调用父组件的 updateParentInformation 函数来更新父组件的状态,从而重新渲染父组件。我在这里有几个问题

  1. 在某些情况下,我们可能有100-150个子组件,在这种情况下我们的父母会重新渲染很多,如何避免这种情况。我们可以通过这段代码来避免这种情况

    ....
     let recievedUpdates = 0
     const …
    Run Code Online (Sandbox Code Playgroud)

reactjs use-effect use-ref

7
推荐指数
1
解决办法
7654
查看次数

在 React 中如何使用 refs 访问映射子项的值?

我有一个应用程序,可以从 GraphQL 数据库中提取数据,然后将其映射到自定义表单组件(数量文本框)中。现在,组件本身保存着各自数量的状态,但我需要能够从父级访问这些值,以便我可以使用应用程序中其他地方的输入来更改数量。我已经查看了这是如何完成的,我认为这可能是我需要的,但我不知道如何应用它:[How to target DOM with React useRef in map][1]

我的应用程序由一个父元素和一个包含输入的顶部栏、一个模态组件以及从 GraphQL 查询填充的元素映射组成。

export default function Home() {
  const [batch, setBatch] = useState([]);
  const [target, setTarget] = useState("");
  const [batchCount, setBatchCount] = useState(0);
  const [cartModalStatus, setCartModalStatus] = useState(false);

  const elementValues = useRef([]);
  const fetcher = query => request("https://data.objkt.com/v2/graphql", query);
  const { data, error } = useSWR(
  `{
    listing(where: {token: {creators: {creator_address: {_eq: ` + target + `}}, supply: {_gt: "0"}}, status: {_eq: "active"}}, order_by: {token: {timestamp: asc}, price: asc}) …
Run Code Online (Sandbox Code Playgroud)

children parent reactjs react-component use-ref

7
推荐指数
1
解决办法
510
查看次数