将引用传递给组件

时间:2019-04-17 23:07:48

标签: reactjs

我知道这可能很简单,但是我似乎找不到解决此问题的方法。感谢您的帮助

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

2 个答案:

答案 0 :(得分:1)

我以前没有使用过裁判,但是请告诉我这是否有帮助:

在下面的示例中,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

答案 1 :(得分:0)

将其更改为此并奏效。

export const InputTime = React.forwardRef((props, ref) => (
  <input
    ref={ref}
    type={"number"}
  />
));