簡體   English   中英

如何遍歷 React 中的 refs 並獲取值?

[英]How to loop through refs in React and get values?

如何遍歷子組件中的段落並在父組件中獲取其 innerHTML 值? 我必須用 refs 來做這件事。

class Parent extends React.Component {
  render() {
    return (
      <Child
        textRef={el => this.textElement = el}
      />
    );
  }
}

function Child(props) {
  return (
    <div>
      <p ref={props.textRef} >abc</p>
      <p ref={props.textRef} >def</p>
      <p ref={props.textRef} >ghi</p>
    </div>
  );
}

您需要維護一個引用數組,並且您應該更新從父組件傳遞的引用。

對於 class 組件,請改用React.createRef ,而componentDidMount用於useEffect

我認為這個例子說明了自己。

/* Logs: ["abc", "def", "ghi"] */

const Parent = () => {
  const textRef = useRef();

  useEffect(() => {
    console.log(textRef.current.map(ref => ref.innerHTML));
  }, []);

  return <Child innerRef={textRef} />;
};

const Child = ({ innerRef }) => {
  const pRefs = useRef([]);

  useEffect(() => {
    innerRef.current = pRefs.current;
  }, [innerRef]);

  return (
    <div>
      <p ref={ref => (pRefs.current[0] = ref)}>abc</p>
      <p ref={ref => (pRefs.current[1] = ref)}>def</p>
      <p ref={ref => (pRefs.current[2] = ref)}>ghi</p>
    </div>
  );
};

如果您需要循環獲取未知數量的p元素,請使用React.Children API

編輯 dank-feather-cs0zr

我使用了一個數組來存儲這些ref 你可以檢查一下。

 function Parent() { const textElements = []; React.useEffect(() => { textElements.forEach(el => console.log(el)) }, [textElements]); return <Child textRef={el => textElements.push(el)} />; } function Child(props) { return ( <div> <p ref={props.textRef}>abc</p> <p ref={props.textRef}>def</p> <p ref={props.textRef}>ghi</p> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<Parent/>, rootElement);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script> <div id="root"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM