Reactjs 如何在使用typescript时在props函数中声明react ref
我需要将引用从一个组件传递到作为道具从另一个组件传入的函数,我需要在typescript中完成 因此,子组件中的相关代码是Reactjs 如何在使用typescript时在props函数中声明react ref,reactjs,typescript,Reactjs,Typescript,我需要将引用从一个组件传递到作为道具从另一个组件传入的函数,我需要在typescript中完成 因此,子组件中的相关代码是 class Login extends Component<IProps, IState> { private emailRef = React.createRef<HTMLInputElement>(); private passRef = React.createRef<HTMLInputElement>();
class Login extends Component<IProps, IState> {
private emailRef = React.createRef<HTMLInputElement>();
private passRef = React.createRef<HTMLInputElement>();
constructor(props?) {
super(props);
}
login = () => {
const email = this.emailRef.current;
const pass = this.passRef.current;
this.props.login(email, pass);
}
很明显,这些都是不好的,需要用更好的东西来取代。如何指定我实际上要在此处传递一个react ref?在
constructor()中声明为
constructor(props?) {
super(props);
this.emailRef = React.createRef();
this.passRef = React.createRef();
}
login:(u:HTMLInputElement,p:HTMLInputElement)=>void
ok-我认为ref是一种包装类型,它给了我一些其他属性,尽管我不得不承认我没有任何特定的理由来进行这种假设。好的,谢谢!哦,当然我忘记了“当ref属性用于HTML元素时,在构造函数中使用React.createRef()创建的ref会接收底层DOM元素作为其当前属性。”为什么?在构造函数中定义引用的必要性是什么?虽然问题不是您所回答的是正确的,从未在类中使用过ref,始终在FC中使用,但从技术上讲,这两个工作:)在typescript中使用this.emailRef在构造函数中给我错误S2339:类型“组件类型”上不存在属性“emailRef”
constructor(props?) {
super(props);
this.emailRef = React.createRef();
this.passRef = React.createRef();
}