我知道这可能很简单,但我似乎无法找到解决这个问题的方法。谢谢你的帮助
<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"}
/>
);
};
我以前没有使用过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
将其更改为此并且有效。
export const InputTime = React.forwardRef((props, ref) => (
<input
ref={ref}
type={"number"}
/>
));