首页 > 解决方案 > Pass a ref to a component

问题描述

I know this is probably simple but I can't seem to find the solution to this problem. Thanks for any help

<InputTime
  ref={el => this.inputTimeOut = el}  // doesn't work
/>

export const InputTime = (props) => {
  return (
    <input          
      ref={props.ref}  // this doesn't seem to be working
      type={"number"}
    />
  );
};

标签: reactjs

解决方案


我以前没有与 refs 合作过,但如果这有帮助,请告诉我:

在下面的示例中,FancyButton 使用 React.forwardRef 获取传递给它的 ref,然后将其转发给它呈现的 DOM 按钮:

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


所以试试:

const ref = React.createRef();
<InputTime
  ref={el => this.inputTimeOut = el} 
/>

export const InputTime = (props) => {
  return (
    <input          
      ref={ref}
      className="InputTime" 
      type={"number"}
    />
  );
};

或者类似的变化。

链接到这里的解释: https ://reactjs.org/docs/forwarding-refs.html#forwarding-refs-to-dom-components


推荐阅读