programing

React.createRef를 사용하는 경우 전류는 항상 null입니다.

cafebook 2023. 3. 4. 15:09
반응형

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을 반환할 것이다.withRouterconnect

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 요소에 할당되기를 기다린 후 해당 요소에 할당된 기능을 실행합니다.

를 사용하고 있는 경우refuseCallback(또는 다른 훅), 잊지 말고 추가해 주세요.ref★★★★★★★★★★★★★★★★★★:

const doSomething = useCallback(() => {
 ref.current?.doIt();
}, [ref]);
<div ref={this.test}>

배정을 해야 요.refDOM ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」 div .

언급URL : https://stackoverflow.com/questions/51693111/current-is-always-null-when-using-react-createref

반응형