标签: use-ref

如何将 ref 传递给相邻组件

我试图在我的 Header 组件中的搜索输入上使用 ref ,它不是我的 ResultsList 组件的高阶组件。我想将焦点集中在 ResultsList 组件的标题搜索输入上。从标题来看它很直观,因为我所要做的就是下面的内容。如果我想在 ResultsList 中创建一个专注于 Header 中的输入元素的按钮该怎么办?我如何通过这个参考?我已经阅读过有关forwardRef的内容,但我没有将我的参考转发。ResultsList 不是 Header 的子项。

import React, { useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';

const Header = () => {
  const searchInput = useRef(null);
  const history = useHistory();

  const [searchValue, setSearchValue] = useState(keyword);

  function handleChange(event) {
    setSearchValue(event.target.value);
  }

  function handleSearch(event) {
    event.preventDefault();
    if(searchValue) {
      history.push(`/search/${searchValue}`);
    } else {
      searchInput.current.focus();
    }
  }

  return (
    <form onSubmit={handleSearch} role="search">
      <input
        value={searchValue}
        onChange={handleChange}
        className="HeaderSearch__input"
        id="header-search-input"
        placeholder="Search a repository" …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks use-ref

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

使用 ref 获取 React 中的 iframe 元素

我有一个包含 iframe 的组件,我想在 React 中访问其内容,我使用 ref 来处理 iframe,如何从 iframe 获取所有锚点标签

这是我的代码:

  const GridGenerator = () => {
      const [loading, setLoading] = useState(true);
      const gridIframe = useRef(null);

  function handleIframe() {
    setLoading(false);
    const iframeItem = gridIframe.current;
    const anchors = iframeItem.contentWindow.getElementsByTagName("a");
  }

  return (
    <div>
      {loading ? <div className={styles.loader} /> : null}
      <iframe
        title="Grid Generator"
        ref={gridIframe}
        src="https://collectearth.users.earthengine.app/view/collect-earth-grid-generator"
        width="100%"
        height="1000px"
        frameBorder={0}
        onLoad={handleIframe}
      />
      <Link to={routes.HOME}>Go Back</Link>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

所以,它运行良好,直到:

const iframeItem = gridIframe.current; 
Run Code Online (Sandbox Code Playgroud)

它返回 iframe 标签,但是这条线不能很好地工作

const anchors = iframeItem.contentWindow.getElementsByTagName("a");
Run Code Online (Sandbox Code Playgroud)

有什么解决办法吗?谢谢

iframe reactjs use-ref

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

为什么尝试在 React 中使用 ref 时 TypeScript 会抱怨?

我正在使用 ref 来为滚动上的元素设置动画。

  const foo = () => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    setAnimClass(
      rect.top >= 0 && rect.bottom <= window.innerHeight ? styles.animClass : ""
    );
  };
Run Code Online (Sandbox Code Playgroud)

这段代码在 next.js 应用程序中运行良好,但是当我在类型脚本模板中使用它时create-react-app,它抱怨Object is possibly 'null'.

if (!ref.current) return;明显,如果 ref.current 不存在,则程序将被返回。但是,TypeScript 在下一行仍然给出错误ref.current.getBoundingClientRect(),指向ref.

如何在不删除打字稿配置中的空检查的情况下解决此问题?

完整文件 - https://github.com/mayank1513/react-contact-app/blob/master/src/components/ContactListItem.tsx

这是完整的项目存储库 - https://github.com/mayank1513/react-contact-app

到目前为止,我已经"strict": false在 tsconfig 中使用绕过了这个问题。但我需要以严格模式进行。

该文件中也存在类似问题。即使在 tsconfig 中设置也无法解决这个问题"strict": false。现在,我只是依赖document.getElementById()-- 大约第 65 行

javascript node.js typescript reactjs use-ref

6
推荐指数
2
解决办法
5679
查看次数

React Native'BottomSheetModalInternalContext'不能为空

我使用BottomSheetModal在底部工作表中显示所有国家/地区的列表。'BottomSheetModalInternalContext' cannot be null!但是,当导航到包含底部模式的屏幕时,我收到错误消息。

我假设发生错误是因为我bottomSheetModalRef用 null 初始化 ref ( ) ,但我不知道如何在不传入 null 的情况下创建 ref 。

完整错误消息的摘录

'BottomSheetModalInternalContext' cannot be null!

This error is located at:
    in ForwardRef(BottomSheetModal)
    in ForwardRef(BottomSheetModal) (at CountryPicker.tsx:89)
    in RCTView (at View.js:34)
    in View (created by ForwardRef)
    in ForwardRef (at CountryPicker.tsx:74)
    ...
Run Code Online (Sandbox Code Playgroud)
//CountryPicker.tsx
import React, { useRef, useState, useEffect, useMemo } from 'react'
import {
  ActivityIndicator,
  TextInput,
  TouchableOpacity,
  StyleSheet,
} from 'react-native'
import axios from 'axios'
import { BottomSheetFlatList, BottomSheetModal } …
Run Code Online (Sandbox Code Playgroud)

javascript react-native react-ref use-ref

6
推荐指数
1
解决办法
4432
查看次数

在 Reactjs 中使用 useRef 从父函数调用子函数

该代码是使用 React 功能组件编写的。

单击父级中的按钮后,应触发函数 showAlert。这就是要求。

目前在父组件childRef.current中无法调用showAlert()函数。我收到打字稿错误

Property 'showAlert' does not exist on type 'ForwardRefExoticComponent<RefAttributes<unknown>>'

父功能组件代码

import React, { forwardRef, useRef, useImperativeHandle } from 'react';
import Child from './Child';
export default function App() {
  const childRef = useRef<typeof Child>(Child);
  return (
    <div className="container">

      <Child ref={childRef} />
      <button
        onClick={() => { childRef.current.showAlert() }}
      >
        Call Function
            </button>
      
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

子功能组件

import React, { forwardRef, useRef, useImperativeHandle } from 'react';

const Child = forwardRef((props, ref) => {
    useImperativeHandle( …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs use-ref

5
推荐指数
1
解决办法
9769
查看次数

在多个输入元素中使用单个 ref 对象

我有一个包含许多输入元素的表单。我想访问父组件中这些输入的值。为此,我可以使用状态,但目前我正在探索引用的使用。我知道可以这样记录输入的值(以便对象inputRef随着输入值的变化而更新)

const inputRef = useRef()

return(
  <input id = "example" ref = {inputRef} />
);
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以在多个输入中使用相同的 ref 对象,例如inputRef.current使用输入 ID 作为键的对象。

例如:

inputRef = useRef()

return(
  <>
    <input id = "fname" ref = {"set inputRef.current.fname"} />
    <input id = "lname" ref = {"set inputRef.current.lname"} />
    <input id = "email" ref = {"set inputRef.current.email"} />
  </>
);
Run Code Online (Sandbox Code Playgroud)

这种方法可以节省创建多个 ref 对象的冗长过程。

forms input ref reactjs use-ref

5
推荐指数
1
解决办法
5767
查看次数

使用 Ref 数组代替单个 Ref

我在地图循环内使用 ref 。我需要一个引用数组问题是引用仅针对列表中生成的最后一个元素这是我准备的示例,我需要通过引用列表在地图循环内的所有生成元素上运行自定义钩子

我正在寻找一种不引入另一个组件的方法

import React, { useRef, useState, useEffect, useCallback } from "react";

/// throttle.ts
export const throttle = (f) => {
  let token = null,
    lastArgs = null;
  const invoke = () => {
    f(...lastArgs);
    token = null;
  };
  const result = (...args) => {
    lastArgs = args;
    if (!token) {
      token = requestAnimationFrame(invoke);
    }
  };
  result.cancel = () => token && cancelAnimationFrame(token);
  return result;
};

const id = (x) => x;
const useDraggable = ({ onDrag …
Run Code Online (Sandbox Code Playgroud)

javascript draggable reactjs react-hooks use-ref

5
推荐指数
1
解决办法
614
查看次数

使用 useRef 或 createRef 而不是内联引用有什么优点?

我正在进行代码审查,发现另一位开发人员编写的代码,例如:

function sampleComponent() {
       let divRef = {};
    
       return (
        <div ref={(el) => { divRef = el }}></div>
       )
    }
Run Code Online (Sandbox Code Playgroud)

然后使用 divRef 作为 DOM 元素的引用。

然而,我知道的模式是createRef在类组件中使用,useRef在功能组件中使用钩子。甚至 ReactJS 官方https://reactjs.org/docs/refs-and-the-dom.html也表示要避免未来 React 版本的内联引用。这是一个要写的遗留模式吗?

到目前为止我能研究的是,内联会ref渲染函数两次,因此建议避免。

我想知道对此还有什么其他解释?

ref reactjs use-ref create-ref

4
推荐指数
1
解决办法
1630
查看次数

如何使用 Typescript 在 React 中定义 &lt;video&gt; 引用的类型?

我正在尝试使用 React.js 中的 ref 来控制视频的播放/暂停状态,我的代码可以工作,但是我正在尝试解决 tslint 错误:

function App() {
    const playVideo = (event:any) => {
        video.current.play()
    }
    const video = useRef(null)

    return (
        <div className="App">
            <video ref={video1} loop src={bike}/>
        </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

这会导致

TS2531: Object is possibly 'null'.
Run Code Online (Sandbox Code Playgroud)

所以,我试图改变const video = useRef(null)const video = useRef(new HTMLVideoElement())

我得到: TypeError: Illegal constructor

我也试过:const video = useRef(HTMLVideoElement) 结果是:

TS2339: Property 'play' does not exist on type '{ new (): HTMLVideoElement; prototype: HTMLVideoElement; }'
Run Code Online (Sandbox Code Playgroud)

html dom typescript reactjs use-ref

4
推荐指数
1
解决办法
1301
查看次数

在 useRef 上使用 focus 会引发错误:“属性 'focus' 在类型 'never' 上不存在”

  const textInputRef = useRef();
  useEffect(() => {
    if (textInputRef && textInputRef.current) {
      textInputRef.current?.focus(); // property 'focus' does not exist on type 'never' 
    }
  }, []);

  return (
      <input ref={textInputRef} />
  )
Run Code Online (Sandbox Code Playgroud)

线textInputRef.current?.focus()正在抛property 'focus' does not exist on type 'never'

我在 React 16.13.1、typescript 4.0.2 上使用钩子和函数组件

typescript reactjs use-ref

4
推荐指数
1
解决办法
2799
查看次数