我使用Typescript与React。我有麻烦理解如何使用参考,以获得静态类型和智能感知的反应节点引用的参考。我的代码如下。

import * as React from 'react';

interface AppState {
    count: number;
}

interface AppProps {
    steps: number;
}

interface AppRefs {
    stepInput: HTMLInputElement;
}

export default class TestApp extends React.Component<AppProps, AppState> {

constructor(props: AppProps) {
    super(props);
    this.state = {
        count: 0
    };
}

incrementCounter() {
    this.setState({count: this.state.count + 1});
}

render() {
    return (
        <div>
            <h1>Hello World</h1>
            <input type="text" ref="stepInput" />
            <button onClick={() => this.incrementCounter()}>Increment</button>
            Count : {this.state.count}
        </div>
    );
}}

当前回答

首先添加一个导入

import React, { useRef } from "react";

那么这个

const studentCapacityRef = useRef<HTMLInputElement>(null);

或者这个

const studentCapacityRef = useRef<HTMLAreaElement>(null);

或者这个

const studentCapacityRef = useRef<HTMLDivElement>(null);

等等……

其他回答

首先添加一个导入

import React, { useRef } from "react";

那么这个

const studentCapacityRef = useRef<HTMLInputElement>(null);

或者这个

const studentCapacityRef = useRef<HTMLAreaElement>(null);

或者这个

const studentCapacityRef = useRef<HTMLDivElement>(null);

等等……

在这种情况下,我总是这样做 抓住裁判

输入:htmlinterment =反应。

要像React文档中推荐的那样使用回调样式(https://facebook.github.io/react/docs/refs-and-the-dom.html),你可以在类中添加一个属性定义:

export class Foo extends React.Component<{}, {}> {
// You don't need to use 'references' as the name
references: {
    // If you are using other components be more specific than HTMLInputElement
    myRef: HTMLInputElement;
} = {
    myRef: null
}
...
 myFunction() {
    // Use like this
    this.references.myRef.focus();
}
...
render() {
    return(<input ref={(i: any) => { this.references.myRef = i; }}/>)
}

当你有一个元素数组的时候,你可以这样做:

const textInputRefs = useRef<(HTMLDivElement | null)[]>([])

...

const onClickFocus = (event: React.BaseSyntheticEvent, index: number) => {
    textInputRefs.current[index]?.focus()
};

...

{items.map((item, index) => (
    <textInput
        inputRef={(ref) => textInputs.current[index] = ref}
    />
    <Button
        onClick={event => onClickFocus(event, index)}
    />
}
class SelfFocusingInput extends React.Component<{ value: string, onChange: (value: string) => any }, {}>{
    ctrls: {
        input?: HTMLInputElement;
    } = {};
    render() {
        return (
            <input
                ref={(input) => this.ctrls.input = input}
                value={this.props.value}
                onChange={(e) => { this.props.onChange(this.ctrls.input.value) } }
                />
        );
    }
    componentDidMount() {
        this.ctrls.input.focus();
    }
}

把它们放在一个对象中