react 父组件获取子组件输入框的值

最近在做登录的功能
想把输入框的都做成组件
遇到一个问题: 父组件form 怎么拿到子组件输入框的值

解决方法:

采用react新提供的
**React.createRef()**方法

具体代码:
父组件代码

import * as React from 'react';
import Pager from "../components/Pager";
import Input from "../components/Input/Input";
class Login extends React.Component{
    private myUsernameRef: React.RefObject;
    private myPasswordRef: React.RefObject;
    constructor(props:any) {
        super(props);
        this.myUsernameRef = React.createRef();
        this.myPasswordRef = React.createRef();
        this.login=this.login.bind(this);
    }
    componentDidMount(): void {
        console.log(this.myUsernameRef);
        console.log(this.myPasswordRef);
    }
    login(){
        console.log(this.myUsernameRef.current.value);
        console.log(this.myPasswordRef.current.value);
    }

    render(): React.ReactElement> | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
        return 
               
               
               
            
    }
}
export default Login;

子组件

import * as React from 'react';
import './input.css'
interface IInput {
    title?:string
    type?:string
    Mref:React.RefObject;
}
class Input extends React.Component {
    render(): React.ReactElement> | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
        return 
{this.props.title}
; } } export default Input;

运行结果

当点击登录时,取到子组件的值
react 父组件获取子组件输入框的值_第1张图片

你可能感兴趣的:(react,typescript)