简体   繁体   English

如何遍历 React 中的 refs 并获取值?

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

How can I loop through paragraphs in Child component and get its innerHTML value in Parent component?如何遍历子组件中的段落并在父组件中获取其 innerHTML 值? I have to do this with refs.我必须用 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>
  );
}

You need to maintain an array of refs, and also you should update the passed reference from the parent component.您需要维护一个引用数组,并且您应该更新从父组件传递的引用。

For class component use React.createRef instead, and componentDidMount for useEffect .对于 class 组件,请改用React.createRef ,而componentDidMount用于useEffect

I think this example explains itself.我认为这个例子说明了自己。

/* 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>
  );
};

If you need to loop for an unknown number of p elements, use React.Children API .如果您需要循环获取未知数量的p元素,请使用React.Children API

编辑 dank-feather-cs0zr

I've used an array to store those ref .我使用了一个数组来存储这些ref You can check this.你可以检查一下。

 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