【问题标题】:How to loop through refs in React and get values?如何遍历 React 中的 refs 并获取值?
【发布时间】:2020-08-25 21:46:32
【问题描述】:

如何遍历子组件中的段落并在父组件中获取其 innerHTML 值?我必须使用参考来做到这一点。

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

【问题讨论】:

标签: javascript reactjs ref


【解决方案1】:

我使用了一个数组来存储那些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>

【讨论】:

    【解决方案2】:

    您需要维护一个引用数组,并且您应该更新从父组件传递的引用。

    对于类组件,请改用React.createRefcomponentDidMount 用于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

    【讨论】:

      猜你喜欢
      • 2017-08-22
      • 2021-09-21
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 2022-07-28
      • 2012-01-16
      • 1970-01-01
      相关资源
      最近更新 更多