React에서 상태 비저장 구성 요소의 참조에 연결하는 방법은 무엇입니까?
스테이트리스 컴포넌트를 생성하려고 합니다.이 컴포넌트는input
요소의 유효성을 부모 컴포넌트로 확인할 수 있습니다.
다음 예에서는 입력에 문제가 있습니다.ref
부모 개인 정보에는 할당되지 않습니다._emailAddress
소유물.
언제handleSubmit
라고 불리고 있습니다.this._emailAddress
이undefined
제가 놓치고 있는 게 있나요? 아니면 더 나은 방법이 있을까요?
interface FormTestState {
errors: string;
}
class FormTest extends React.Component<void, FormTestState> {
componentWillMount() {
this.setState({ errors: '' });
}
render(): JSX.Element {
return (
<main role='main' className='about_us'>
<form onSubmit={this._handleSubmit.bind(this)}>
<TextInput
label='email'
inputName='txtInput'
ariaLabel='email'
validation={this.state.errors}
ref={r => this._emailAddress = r}
/>
<button type='submit'>submit</button>
</form>
</main>
);
}
private _emailAddress: HTMLInputElement;
private _handleSubmit(event: Event): void {
event.preventDefault();
// this._emailAddress is undefined
if (!Validators.isEmail(this._emailAddress.value)) {
this.setState({ errors: 'Please enter an email address.' });
} else {
this.setState({ errors: 'All Good.' });
}
}
}
const TextInput = ({ label, inputName, ariaLabel, validation, ref }: { label: string; inputName: string; ariaLabel: string; validation?: string; ref: (ref: HTMLInputElement) => void }) => (
<div>
<label htmlFor='txt_register_first_name'>
{ label }
</label>
<input type='text' id={inputName} name={inputName} className='input ' aria-label={ariaLabel} ref={ref} />
<div className='input_validation'>
<span>{validation}</span>
</div>
</div>
);
사용할 수 있습니다.useRef
이후 사용할 수 있는 후크v16.7.0-alpha
.
편집: 현재 운영 환경에 Hooks를 사용하는 것이 좋습니다.16.8.0
해방!
후크를 사용하면 상태를 유지하고 기능 컴포넌트의 부작용을 처리할 수 있습니다.
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
편집: 이제 리액트 훅으로 할 수 있습니다.Ante Gulin의 답변을 참조하십시오.
React like 메서드에 액세스할 수 없습니다(예:componentDidMount
,componentWillReceiveProps
스테이트리스 컴포넌트(등)의 경우,refs
전체 컨보에서 GH에 대한 이 논의를 확인해 주십시오.
스테이트리스란 작성된 인스턴스가 없다는 개념입니다(상태).그 때문에, 접속할 수 없습니다.ref
참조를 첨부할 상태가 없기 때문입니다.
가장 좋은 방법은 컴포넌트가 변경되었을 때 콜백을 전달하고 그 텍스트를 부모 상태에 할당하는 것입니다.
또는 상태 비저장 구성 요소를 모두 제거하고 일반 클래스 구성 요소를 사용할 수 있습니다.
기능 컴포넌트에는 인스턴스가 없으므로 ref 속성을 사용할 수 없습니다.그러나 기능 구성요소의 렌더링 함수 내에서 ref 속성을 사용할 수 있습니다.
function CustomTextInput(props) {
// textInput must be declared here so the ref callback can refer to it
let textInput = null;
function handleClick() {
textInput.focus();
}
return (
<div>
<input
type="text"
ref={(input) => { textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
늦은 감이 있지만 이 솔루션이 훨씬 낫다는 것을 알았습니다.useRef를 사용하는 방법 및 현재 속성에서 속성을 사용할 수 있는 방법에 주의하십시오.
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it
const textInput = useRef(null);
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input
type="text"
ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
TextInput 값은 컴포넌트 상태에 불과합니다.따라서 참조를 사용하여 현재 값을 가져오는 대신(내가 아는 한 일반적으로 잘못된 생각) 현재 상태를 가져올 수 있습니다.
축소판(입력하지 않음):
class Form extends React.Component {
constructor() {
this.state = { _emailAddress: '' };
this.updateEmailAddress = this.updateEmailAddress.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
updateEmailAddress(e) {
this.setState({ _emailAddress: e.target.value });
}
handleSubmit() {
console.log(this.state._emailAddress);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
value={this.state._emailAddress}
onChange={this.updateEmailAddress}
/>
</form>
);
}
}
약간의 배관을 통해 기능적인 컴포넌트에 대한 레퍼런스도 얻을 수 있습니다.
import React, { useEffect, useRef } from 'react';
// Main functional, complex component
const Canvas = (props) => {
const canvasRef = useRef(null);
// Canvas State
const [canvasState, setCanvasState] = useState({
stage: null,
layer: null,
context: null,
canvas: null,
image: null
});
useEffect(() => {
canvasRef.current = canvasState;
props.getRef(canvasRef);
}, [canvasState]);
// Initialize canvas
useEffect(() => {
setupCanvas();
}, []);
// ... I'm using this for a Konva canvas with external controls ...
return (<div>...</div>);
}
// Toolbar which can do things to the canvas
const Toolbar = (props) => {
console.log("Toolbar", props.canvasRef)
// ...
}
// Parent which collects the ref from Canvas and passes to Toolbar
const CanvasView = (props) => {
const canvasRef = useRef(null);
return (
<Toolbar canvasRef={canvasRef} />
<Canvas getRef={ ref => canvasRef.current = ref.current } />
}
언급URL : https://stackoverflow.com/questions/41048546/how-can-i-attach-to-a-stateless-components-ref-in-react
'programing' 카테고리의 다른 글
JSON 파일의 값 변경(파일 쓰기) (0) | 2023.03.18 |
---|---|
Wordpress 제목: 50자를 초과하는 경우 생략 부호 표시 (0) | 2023.03.18 |
Spring REST 서비스: json 응답의 null 개체를 제거하도록 구성하는 방법 (0) | 2023.03.18 |
스프링 임베디드 Kafka를 사용한 @Kafka Listener 테스트 (0) | 2023.03.18 |
리액트 훅을 사용한 상태 갱신 시 비동기 코드 실행 (0) | 2023.03.18 |