我正在试验 React Hooks,我想知道如何使用 useRef 定位元素儿童。实际上,我知道如何使用 useRef 定位一个元素。但是当我尝试将子项分配给变量时遇到了一些问题。
这是一个例子:
import React, { useState, useEffect, useRef } from "react";
import "./styles.css";
export default function App() {
let containerRef = useRef(null);
let title, subtitle;
const myEvent = () => {
console.log(title);
};
useEffect(() => {
title = containerRef.children[0];
subtitle = containerRef.children[1];
}, []);
return (
<div className="App" ref={el => (containerRef = el)}>
<h1 onClick={myEvent}>Hello World!</h1>
<h2>What's going on ?</h2>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
我想访问标题和副标题变量以在 useEffect 之外创建一个函数。我知道我对标题和副标题的第一个声明是错误的。但实际上我不知道如何解决这个问题。我尝试使用useState,但未能解决我的问题。 …
我如何使用带有Typescript的React ref作为可变实例?当前属性似乎被键入为只读。
我正在使用React + Typescript开发一个库,该库与React不会渲染的输入字段进行交互。我想捕获对HTML元素的引用,然后将React事件绑定到它。
const inputRef = useRef<HTMLInputElement>();
const { elementId, handler } = props;
// Bind change handler on mount/ unmount
useEffect(() => {
inputRef.current = document.getElementById(elementId);
if (inputRef.current === null) {
throw new Exception(`Input with ID attribute ${elementId} not found`);
}
handler(inputRef.current.value);
const callback = debounce((e) => {
eventHandler(e, handler);
}, 200);
inputRef.current.addEventListener('keypress', callback, true);
return () => {
inputRef.current.removeEventListener('keypress', callback, true);
};
});
Run Code Online (Sandbox Code Playgroud)
它生成编译器错误: semantic error TS2540: Cannot assign to 'current' because it is a read-only …