React.createRef를 사용하는 경우 전류는 항상 null입니다.
난 이걸 하려고 했어.
뭔가 놓치고 있는 게 틀림없는데 왜 그런 건지 모르겠어요.current
항상 있다null
를 참조해 주세요.
class App extends React.PureComponent {
constructor(props) {
super(props);
this.test = React.createRef();
}
render() {
return <div className="App">current value : {this.test.current + ""}</div>;
}
}
제 테스트 케이스는 이쪽에서 확인하실 수 있습니다.
왜냐하면 당신이 어떤 돔 요소에 ref를 할당하는 것을 잊어버렸기 때문이다.작성만 하고 있습니다.
다음과 같이 적습니다.
class App extends React.PureComponent {
constructor(props) {
super(props);
this.test = React.createRef();
}
handleClick = () => alert(this.test.current.value)
render() {
return (
<div className="App">
<input ref={this.test} />
<button onClick={this.handleClick}>Get Value</button>
</div>
)
}
}
이것이 OP의 문제에 대한 해결책이 아니라는 것을 알지만, 구글 검색에서 나오는 사람들에게 ref.current가 null이 될 수 있는 방법 중 하나는 ref가 연결된 컴포넌트일 경우입니다.react-redux 연결이나 Router를 사용하는 경우와 같습니다.react-redux의 경우 솔루션은 연결하는 네 번째 옵션에서 forwardRef:true를 전달하는 것입니다.
React.createRef()는 비동기이므로 componentDidMount의 ref에 액세스하려고 하면 null을 반환하고 나중에 참조하는 컴포넌트의 속성을 반환합니다.
componentDidMount(): void {
if (this.viewShot && this.viewShot.current) {
this.viewShot.current.capture().then((uri) => {
console.log('do something with ', uri);
});
}
}
이것이 이 컨텍스트에서 React.createRef()를 사용하는 올바른 방법입니다.
놓치셨네요ref={this.test}
소품
return (
<div className="App" ref={this.test}>
current value : {this.test.current + ""}
</div>
);
이 문제는 다음과 같은 경우에 발생할 수 있습니다.
- 레퍼런스를 컴포넌트에 전달하는 것을 잊었습니다.
this.test
질문에서.
<Component ref={this.test} />
- 참조 소품이 전달되는 컴포넌트가 포장된 Redux를 사용하고 있습니다.
connect
방법 및 그에 따른this.test.current
이러한 종류의 컴포넌트가 동작하도록 하기 위해 Redux 래퍼를 가리킬 때 null을 반환합니다.forwardRef: true
예:
connect(mapStateToProps, mapDispatchToProps, null, {forwardRef: true})(Component)
- 사용하시는 경우
withRouter
그리고.connect
여기 하나 말고 두 마리 토끼를 먹고this.test.current
이를 극복하기 위해 반드시 null을 반환할 것이다.withRouter
랩connect
withRouter(connect(mapStateToProps, mapDispatchToProps, null, {forwardRef: true})(Component))
그리고 나서.
<Component wrappedComponentRef={ref => this.test = ref} />
wrappedComponentRef
포장된 컴포넌트를 다음과 같이 사용할 수 있도록 하기 위해 사용하는 받침대입니다.forwardRef: true
, 여기의 문서에서 찾을 수 있습니다.
React 버전 17.0.2에서는 refs 및 비동기 상태가 변경되었습니다.업데이트 후 다음과 같은 코드가 제대로 작동하지 않습니다.
import {useRef} from 'react';
import './kind.css'
const Kind = ({prop}) => {
// defining the ref
const kindRef = useRef('')
// print the ref to the console
console.log(kindRef)
return (
<div ref={kindRef} className="kind-container" >
<div className="kind" data-kind='drink'>Drink</div>
<div className="kind" data-kind='sweet'>Sweet</div>
<div className="kind" data-kind='lorem'>lorem</div>
<div className="kind" data-kind='ipsum'>ipsum</div>
<div className="kind" data-kind='ipsum' >food</div>
</div>
);
}
export default Kind;
ref를 초기화한 후 돔에 할당하는 데 시간이 걸립니다.Javascript는 동기 언어이므로 참조가 초기화되기를 기다리지 않고 로그로 바로 건너뜁니다.
이 문제를 해결하려면useEffect
이것처럼.
import { useRef, useEffect} from 'react';
import './kind.css'
const Kind = ({prop}) => {
// defining the ref
const kindRef = useRef('')
// using 'useEffect' will help us to do what ever you want to your ref varaible,
// by waiting to letting the elements to mount:'mount means after the elements get inserted in the page' and then do what you want the ref
useEffect(()=>{
// print the ref to the console
console.log(kindRef)
})
return (
<div ref={kindRef} className="kind-container" >
<div className="kind" data-kind='drink'>Drink</div>
<div className="kind" data-kind='sweet'>Sweet</div>
<div className="kind" data-kind='lorem'>lorem</div>
<div className="kind" data-kind='ipsum'>ipsum</div>
<div className="kind" data-kind='ipsum' >food</div>
</div>
);
}
export default Kind;
useEffect
는 참조가 DOM 요소에 할당되기를 기다린 후 해당 요소에 할당된 기능을 실행합니다.
를 사용하고 있는 경우ref
에useCallback
(또는 다른 훅), 잊지 말고 추가해 주세요.ref
★★★★★★★★★★★★★★★★★★:
const doSomething = useCallback(() => {
ref.current?.doIt();
}, [ref]);
<div ref={this.test}>
배정을 해야 요.ref
DOM ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」 div .
언급URL : https://stackoverflow.com/questions/51693111/current-is-always-null-when-using-react-createref
'programing' 카테고리의 다른 글
여러 개의 대소문자가 있는 Tymleaf 스위치 문 (0) | 2023.03.04 |
---|---|
Mongo 그룹 및 푸시: 모든 필드 푸시 (0) | 2023.03.04 |
스프링 부트 2 및 마이크로미터를 사용하여 서비스 방법을 측정하는 방법 (0) | 2023.02.27 |
사이드바 외부에서 위젯을 사용하시겠습니까? (0) | 2023.02.27 |
jQuery Ajax 함수의 전체 양식을 데이터로 전달합니다. (0) | 2023.02.27 |