将ref传递给组件

问题描述 投票:0回答:2

我知道这可能很简单,但我似乎无法找到解决这个问题的方法。谢谢你的帮助

<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
2个回答
1
投票

我以前没有使用过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


0
投票

将其更改为此并且有效。

export const InputTime = React.forwardRef((props, ref) => (
  <input
    ref={ref}
    type={"number"}
  />
));
© www.soinside.com 2019 - 2024. All rights reserved.