【问题标题】:How to provide a ref to a child element如何为子元素提供引用
【发布时间】:2021-03-27 00:02:27
【问题描述】:

我有两个功能:

export default function Example() {
  return (
    <Widget>
      <img src="/hello" />
    </Widget>
  )
}

export default function Widget() {
  const ref = useRef(null)
  return (
    <div>
      {children}
    </div>
  )
}

如何将“ref”应用于Example 的图像元素?有没有办法始终将其应用于第一个子元素?

【问题讨论】:

  • 那:a)似乎需要对子元素进行一些更改,有没有办法做到这一点? b)似乎要求我实例化我将 ref 传递给的子元素,在这个例子中我不能。 @TusharGupta-curioustushar

标签: node.js reactjs


【解决方案1】:

你可以使用cloneElement,它可以帮助我们克隆并返回一个新的 React 元素,使用一个元素作为起点。这样,我们可以将 ref 添加到 element props,首先,我们创建一个 children 数组,然后将我们的 ref 添加到第一个,例如:

function Wrapper({ children }) {
  const testRef = React.useRef(undefined);

  const addReftoFirstChild = (chilrens, ref) => {
    let elements = React.Children.toArray(chilrens);

    return [React.cloneElement(elements[0], { ref })].concat(elements.slice(1));
  };

  return (
    <>
      {addReftoFirstChild(children, testRef)}

      <button onClick={() => console.log(testRef.current)}>Test Ref!</button>
    </>
  );
}

function App() {
  return (
    <Wrapper>
      <img
        src='https://www.publicdomainpictures.net/pictures/80000/velka/odd-eyed-kitten.jpg'
        width={200}
        height={125}
      />
      <img
        src='https://c.files.bbci.co.uk/12A9B/production/_111434467_gettyimages-1143489763.jpg'
        width={200}
        height={125}
      />
    </Wrapper>
  );
}

【讨论】:

    【解决方案2】:

    你可以使用 React 的 Context。

    const MyContext = React.createContext();
    
    function Widget(props) {
      const myRef = useRef(null);
      useEffect(() => {
        myRef.current.focus();
      });
      return (
        <MyContext.Provider value={myRef}>{props.children}</MyContext.Provider>
      );
    }
    
    function Example() {
      return (
        <Widget>
          <MyContext.Consumer>
            {(forwardedRef) => <input type="text" ref={forwardedRef} />}
          </MyContext.Consumer>
        </Widget>
      );
    }
    

    我为您创建了一个演示: https://codesandbox.io/s/prod-voice-mkrcp

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多