source

상위 구성 요소의 하위 구성 요소 참조에 액세스하는 방법

nicesource 2023. 3. 5. 09:54
반응형

상위 구성 요소의 하위 구성 요소 참조에 액세스하는 방법

제가 만약에 이런 게 있다면

<Parent>
  <Child1 />
  <Child2 />
  <Child3 />
</Parent>

제가 하고 싶은 곳은 '하다'입니다.Child2는 가지 where where where where where where where where where where whererefs="child2refs" 좋을까요가가어 떻떻 ?럴? ???

React 16.3 이전 버전에 권장

피할 수 없는 경우 React 문서에서 추출된 권장 패턴은 다음과 같습니다.

import React, { Component } from 'react';

const Child = ({ setRef }) => <input type="text" ref={setRef} />;

class Parent extends Component {
    constructor(props) {
        super(props);
        this.setRef = this.setRef.bind(this);
    }

    componentDidMount() {
        // Calling a function on the Child DOM element
        this.childRef.focus();
    }

    setRef(input) {
        this.childRef = input;
    }

    render() {
        return <Child setRef={this.setRef} />
    }
}

부모 부모에게 바인드된 소품으로 기능을 전달합니다. thisReact가 Child's에 전화를 걸면 refsetRefChild's가 할당됩니다. ref부모에게 childRef★★★★★★★★★★★★★★★★★★.

반응 > = 16.3에 권장

참조 전달은 일부 컴포넌트가 수신한 참조를 가져와 하위 컴포넌트에게 전달(즉, "전송")할 수 있는 옵션 입력 기능입니다.

델은 다음 컴포넌트를 생성하여refReact.forwardRef반품된 컴포넌트 참조 소품은 반품 타입과 동일해야 합니다.React.createRef. 마다 을 지정합니다 리액트(Respect) DOM(DOM)currentref" " 로 되었습니다.React.createRef는본 DOM 드다 。

import React from "react";

const LibraryButton = React.forwardRef((props, ref) => (
  <button ref={ref} {...props}>
    FancyButton
  </button>
));

class AutoFocus extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
    this.onClick = this.onClick.bind(this);
  }

  componentDidMount() {
    this.childRef.current.focus();
  }

  onClick() {
    console.log("fancy!");
  }

  render() {
    return <LibraryButton onClick={this.onClick} ref={this.childRef} />;
  }
}

Forwarding refs HOC 예시

생성된 컴포넌트는 다음 컴포넌트를 전송하고 있습니다.ref자노드로 이동합니다.

function logProps(Component) {
  class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);
    }

    render() {
      const {forwardedRef, ...rest} = this.props;

      // Assign the custom prop "forwardedRef" as a ref
      return <Component ref={forwardedRef} {...rest} />;
    }
  }

  // Note the second param "ref" provided by React.forwardRef.
  // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
  // And it can then be attached to the Component.
  return React.forwardRef((props, ref) => {
    return <LogProps {...props} forwardedRef={ref} />;
  });
}

React 문서의 Forwarding Refs를 참조하십시오.

  1. 하위 구성 요소 내에서 필요한 노드에 참조를 추가합니다.
  2. 상위 구성 요소 내부에서 하위 구성 요소에 참조를 추가합니다.
/*
* Child component
*/
class Child extends React.Component {
  render() {
    return (
      <div id="child">
        <h1 ref={(node) => { this.heading = node; }}>
          Child
        </h1>
      </div>
    );
  }
}

/*
 * Parent component
 */
class Parent extends React.Component {
  componentDidMount() {
    // Access child component refs via parent component instance like this
    console.log(this.child.heading.getDOMNode());
  }

  render() {
    return (
      <div>
        <Child
          ref={(node) => { this.child = node; }}
        />
      </div>
    );
  }
}

데모: https://codepen.io/itsfadnis/pen/aLWVVx?editors=0011

다음은 Ref를 사용한 입력에 초점을 맞추는 예입니다(React 16.8.6에서 테스트됨).

Child 구성 요소:

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return (<input type="text" ref={this.myRef} />);
  }
}

Child 컴포넌트가 내부에 있는 부모 컴포넌트:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }
  componentDidMount() {
    this.childRef.current.myRef.current.focus();
  }
  render() {
    return <Child ref={this.childRef} />;
  }
}

ReactDOM.render(
    <Parent />,
    document.getElementById('container')
);

this.props.children을 가진 부모 컴포넌트:

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.childRef = React.createRef();
    }
    componentDidMount() {
        this.childRef.current.myRef.current.focus();
    }
    render() {
        const ChildComponentWithRef = React.forwardRef((props, ref) =>
            React.cloneElement(this.props.children, {
                ...props,
                ref
            })
        );
        return <ChildComponentWithRef ref={this.childRef} />
    }
}

ReactDOM.render(
    <Parent>
        <Child />
    </Parent>,
    document.getElementById('container')
);

아이들에게 과 같이 접근합니다.this.props.children 후, 각 는 자신의 , 을 ref그 위에 재산으로.

참조 전달을 사용하면 상위에서 하위로 참조를 전달할 수 있습니다.

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
  1. React.createRef를 호출하여 React ref를 만들고 ref 변수에 할당합니다.
  2. 참조를 JSX 속성으로 지정하여 에 전달합니다.
  3. React는 ref를 (ref, ref) => ...에 전달합니다.function inside forwardRef를 두 번째 인수로 지정합니다.
  4. 이 ref 인수를 JSX 속성으로 지정하여 로 전송합니다.
  5. ref가 연결되면 ref.current가 DOM 노드를 가리킵니다.

주 두 번째 ref 인수는 React.forwardRef 호출을 사용하여 컴포넌트를 정의하는 경우에만 존재합니다.일반 함수 또는 클래스 구성요소는 ref 인수를 수신하지 않으며, ref는 소품에서도 사용할 수 없습니다.

참조 전달은 DOM 컴포넌트에 한정되지 않습니다.클래스 컴포넌트 인스턴스에도 참조를 전달할 수 있습니다.

레퍼런스:대응 문서

만약 당신이 가진 모든 것이props.children:

const Parent = (p: {children: JSX.Element}) => {
    const childRef = useRef()

    return React.cloneElement(p.children, { ref: childRef })
}
<Parent>
  <SingleChild />
</Parent>

주의: 자녀분에게 다음 기능이 없으면 실패합니다.ref,예.React.Fragment.

이 가이드는 https://github.com/yannickcr/eslint-plugin-react/issues/678에서 꽤 잘 설명한 것 같습니다.

class Field extends Component {
  const { inputRef } = this.props;
  render() {
    return (
      <input type="text" ref={inputRef} />
    )
  }
}

class MyComponent extends Component {
  componentDidMount() {
    this.inputNode.focus();
  }

  render() {
    return (
      <div>
        Hello, <Field inputRef={node => this.inputNode = node} />
      </div>
    )
  }
}

동적 컴포넌트의 문제를 해결하는 방법은 다음과 같습니다.

상위 구성 요소에서 하위 구성 요소에 대한 참조를 동적으로 만듭니다. 예를 들어 다음과 같습니다.

class Form extends Component {
    fieldRefs: [];

    // dynamically create the child references on mount/init
    componentWillMount = () => {
        this.fieldRefs = [];
        for(let f of this.props.children) {
            if (f && f.type.name == 'FormField') {
                f.ref = createRef();
                this.fieldRefs.push(f);
            }
        }
    }

    // used later to retrieve values of the dynamic children refs
    public getFields = () => {
        let data = {};

        for(let r of this.fieldRefs) {
            let f = r.ref.current;
            data[f.props.id] = f.field.current.value;
        }

        return data;
    }
}

Child 컴포넌트(<폼필드/>)는 부모로부터 참조되는 독자적인 '필드' 참조를 실장합니다.

class FormField extends Component {
    field = createRef();
    
    render() {
        return(
            <input ref={this.field} type={type} />
        );
    }
}

그런 다음 기본 페이지인 "부모" 구성 요소에서 다음 항목을 사용하여 참조에서 필드 값을 가져올 수 있습니다.

class Page extends Component {
    form = createRef();

    onSubmit = () => {
        let fields = this.form.current.getFields();
    }

    render() {
        return (
            <Form ref={this.form}>
                <FormField id="email" type="email" autoComplete="email" label="E-mail" />
                <FormField id="password" type="password" autoComplete="password" label="Password" />

                <div class="button" onClick={this.onSubmit}>Submit</div>
            </Form>
        );
    }
}

메인 <에서 모든 일반 폼 기능을 캡슐화시키고 싶었기 때문입니다.양식 /> 구성 요소 세트 구성 요소 세트 구성 요소 세트 및 스타일 구성 요소를 사용할 수 있는 유일한 방법은 하위 구성 요소를 사용할 수 있습니다.< 양식 필드/> 항목/> 항목 내에서 항목다른 > 페이지/> 구성 요소)에 있습니다.

따라서 일부에서는 이를 해킹으로 간주할 수도 있지만, 이는 React가 부모로부터 실제 'ref'를 차단하려는 시도와 마찬가지로 우스꽝스러운 설계라고 생각하지만 합리화하고자 하는 것입니다.

언급URL : https://stackoverflow.com/questions/37647061/how-do-i-access-refs-of-a-child-component-in-the-parent-component

반응형