유형 스크립트로 반응에서 참조를 사용하는 방법
리액트와 함께 타이프스크립트를 사용하고 있습니다.참조가 참조하는 반응 노드에 대해 정적 타이핑과 인텔리전스를 얻기 위해 참조를 사용하는 방법을 이해하는 데 어려움을 겪고 있습니다.제 코드는 다음과 같습니다.
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>
);
}}
React 16.3+를 사용하는 경우 참조를 생성하는 권장 방법은React.createRef().
class TestApp extends React.Component<AppProps, AppState> {
private stepInput: React.RefObject<HTMLInputElement>;
constructor(props) {
super(props);
this.stepInput = React.createRef();
}
render() {
return <input type="text" ref={this.stepInput} />;
}
}
, 「」는ref의 「」current컴포넌트/ "/DOM"으로 됩니다.null'어리다'를 사용해서 할 수 요.this.stepInput.current.
것은, 을 참조해 주세요.RefObject@apeceofbart의 답변 또는 PR을 참조하십시오. createRef()을 사용하다
이전 버전의 React(16.3 미만)를 사용하고 있거나 참조 설정 및 설정 해제 시기를 보다 세밀하게 제어해야 하는 경우 "콜백 참조"를 사용할 수 있습니다.
class TestApp extends React.Component<AppProps, AppState> {
private stepInput: HTMLInputElement;
constructor(props) {
super(props);
this.stepInput = null;
this.setStepInputRef = element => {
this.stepInput = element;
};
}
render() {
return <input type="text" ref={this.setStepInputRef} />
}
}
는 "React"를합니다.ref하고 DOM 요소를 사용하여 .null '접근하다'를 사용해서 간단하게 할 수 있습니다.this.stepInput.
「 」를 정의함으로써,ref인라인 함수가 아닌 클래스에서의 바인드 방식으로서의 콜백(이 응답의 이전 버전과 같이)을 사용하면 업데이트 중에 콜백이 두 번 호출되는 것을 방지할 수 있습니다.
예전에는 API가 있었는데ref 속성은 문자열이었지만(Aksar Patel의 답변 참조), 몇 가지 문제로 인해 문자열 참조는 강력히 권장되지 않으며 최종적으로 삭제됩니다.
2018년 5월 22일 편집되어 React 16.3의 새로운 참조 방법을 추가.새로운 방법이 있다고 지적해 주셔서 @ape of bart에 감사드립니다.
React.createRef(이것들)
class ClassApp extends React.Component {
inputRef = React.createRef<HTMLInputElement>();
render() {
return <input type="text" ref={this.inputRef} />
}
}
React.useRef / comp ('/'/'comp')
a) Use readonly refs for React-managed DOM nodes:
const FunctionApp = () => {
// note the passed-in `null` arg ----------------v
const inputRef = React.useRef<HTMLInputElement>(null)
return <input type="text" ref={inputRef} />
}
inputRef.current로 값을 초기화함으로써 속성이 됩니다.null.
const FunctionApp = () => {
const renderCountRef = useRef(0)
useEffect(() => {
renderCountRef.current += 1
})
// ... other render code
}
:하지 마십시오useRef이 케이스에서는 - 이 경우,renderCountRef「」라고 입력합니다.readonly(예를 참조).제공이 필요한 경우null초기값으로 다음을 수행합니다.
const renderCountRef = useRef<number | null>(null)
콜백 참조(둘 다)
// Function component example, class analogue
const FunctionApp = () => {
const handleDomNodeChange = (domNode: HTMLInputElement | null) => {
// ... do something with changed dom node.
}
return <input type="text" ref={handleDomNodeChange} />
}
주의: String Refs는 레거시로 간주되며 이 답변의 범위에서는 생략됩니다.
(지금까지 하고 있는) 한 가지 방법은 수동으로 설정하는 것입니다.
refs: {
[string: string]: any;
stepInput:any;
}
더 좋은 게터 기능으로 마무리할 수도 있습니다(예: 여기).
stepInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.stepInput);
Refact 16.3을 추가하는 방법은 Jeff Bowen이 답변에서 지적한 대로 Refact.createRef를 사용하는 것입니다.그러나 Typescript를 사용하여 참조를 더 잘 입력할 수 있습니다.
이 예에서는 입력 요소에 ref를 사용하고 있습니다.그래서 그들은 내가 할 수 있는 방법:
class SomeComponent extends React.Component<IProps, IState> {
private inputRef: React.RefObject<HTMLInputElement>;
constructor() {
...
this.inputRef = React.createRef();
}
...
render() {
<input type="text" ref={this.inputRef} />;
}
}
이렇게 하면 해당 ref를 사용할 때 모든 입력 방법에 액세스할 수 있습니다.
someMethod() {
this.inputRef.current.focus(); // 'current' is input node, autocompletion, yay!
}
커스텀 컴포넌트에서도 사용할 수 있습니다.
private componentRef: React.RefObject<React.Component<IProps>>;
예를 들어 다음과 같은 소품을 사용할 수 있습니다.
this.componentRef.current.props; // 'props' satisfy IProps interface
사용하시는 경우React.FC, 를 추가합니다.HTMLDivElement인터페이스:
const myRef = React.useRef<HTMLDivElement>(null);
그리고 다음과 같이 사용합니다.
return <div ref={myRef} />;
편집: 이것은 더 이상 Typescript와 함께 참조를 사용하는 올바른 방법이 아닙니다.Jeff Bowen의 답변을 보고 이를 상향 투표하여 가시성을 높입니다.
문제의 답을 찾았습니다.클래스 내에서 다음과 같이 ref를 사용합니다.
refs: {
[key: string]: (Element);
stepInput: (HTMLInputElement);
}
올바른 방향을 가르쳐 주셔서 @basarat에 감사드립니다.
요소가 배열되어 있을 때 이를 수행하는 방법을 모색하는 사용자:
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)}
/>
}
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; }}/>)
}
타이프스크립트 사용자의 경우 생성자가 필요하지 않습니다.
...
private divRef: HTMLDivElement | null = null
getDivRef = (ref: HTMLDivElement | null): void => {
this.divRef = ref
}
render() {
return <div ref={this.getDivRef} />
}
...
전달하고 싶은 경우ref, Props 인터페이스에서는 를 사용해야 합니다.RefObject<CmpType>에서 타이핑하다.import React, { RefObject } from 'react';
완전한 예가 없는 상태에서 React 및 TypeScript를 사용할 때 사용자 입력을 받기 위한 간단한 테스트 스크립트를 소개합니다.다른 코멘트와 링크 https://medium.com/ @basarat/syslog-refs-for-syscript-9a07419f807#.cdrghertm에 따라 부분적으로 작성됩니다.
/// <reference path="typings/react/react-global.d.ts" />
// Init our code using jquery on document ready
$(function () {
ReactDOM.render(<ServerTime />, document.getElementById("reactTest"));
});
interface IServerTimeProps {
}
interface IServerTimeState {
time: string;
}
interface IServerTimeInputs {
userFormat?: HTMLInputElement;
}
class ServerTime extends React.Component<IServerTimeProps, IServerTimeState> {
inputs: IServerTimeInputs = {};
constructor() {
super();
this.state = { time: "unknown" }
}
render() {
return (
<div>
<div>Server time: { this.state.time }</div>
<input type="text" ref={ a => this.inputs.userFormat = a } defaultValue="s" ></input>
<button onClick={ this._buttonClick.bind(this) }>GetTime</button>
</div>
);
}
// Update state with value from server
_buttonClick(): void {
alert(`Format:${this.inputs.userFormat.value}`);
// This part requires a listening web server to work, but alert shows the user input
jQuery.ajax({
method: "POST",
data: { format: this.inputs.userFormat.value },
url: "/Home/ServerTime",
success: (result) => {
this.setState({ time : result });
}
});
}
}
반응 유형 정의에서
type ReactInstance = Component<any, any> | Element;
....
refs: {
[key: string]: ReactInstance
};
따라서 다음과 같이 참조 요소에 액세스할 수 있습니다.
stepInput = () => ReactDOM.findDOMNode(this.refs['stepInput']);
참조 지수를 재정의하지 않습니다.
@manakor가 언급했듯이 다음과 같은 오류가 발생할 수 있습니다.
속성 '단계'입력'이 유형 '{ [key: string]에 없습니다.컴포넌트 | 요소 }
refs를 재정의하는 경우(사용하는 IDE 및 ts 버전에 따라 다름)
다른 접근방식을 덧붙이자면, 다음과 같이 레퍼리를 캐스팅할 수 있습니다.
let myInputElement: Element = this.refs["myInput"] as Element
난 항상 이렇게 해요, 그럴 땐 심판이라도 잡으려고
let input: HTMLInputElement = ReactDOM.findDOMNode<HTMLInputElement>(this.refs.input);
FIRST ADD AN IMPORT
import React, { useRef } from "react";
그리고 이거
const studentCapacityRef = useRef<HTMLInputElement>(null);
또는 이것
const studentCapacityRef = useRef<HTMLAreaElement>(null);
또는 이것
const studentCapacityRef = useRef<HTMLDivElement>(null);
기타...
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();
}
}
그것들을 어떤 물건에 넣다.
언급URL : https://stackoverflow.com/questions/33796267/how-to-use-refs-in-react-with-typescript
'programing' 카테고리의 다른 글
| C#의 JSON 어레이 시리얼 해제 (0) | 2023.03.26 |
|---|---|
| 타이프 스크립트의 소품으로 useState 전달 (0) | 2023.03.26 |
| 현재 활성 데이터Spring Boot에서 소스 참조 가져오기 (0) | 2023.03.21 |
| Ajax에서 Asynchronous는 무엇을 의미합니까? (0) | 2023.03.21 |
| 전자를 사용하여 폴더 경로를 얻는 방법 (0) | 2023.03.21 |