如何从钩子反应组件获取TextField(Material-UI)值?

时间:2020-09-01 13:33:15

标签: reactjs typescript material-ui react-hooks use-ref

我将Material-UI与react结合使用,其组件类似于:

const UserDetail = (props: ListDetailProps) => {
    const oldpassword = useRef<TextFieldProps>(null);
    const newpassword = useRef<TextFieldProps>(null);
    const againpassword = useRef<TextFieldProps>(null);
    const handlePasswordChange = async () => {
        console.log(newpassword.current?.value)    //expect the password value but undefined get
        console.log(againpassword.current?.value)  //expect the password value but undefined get
    }
    return (<>
        <p>old password: <TextField ref={oldpassword} label="old password" type="password" /></p>
        <p>new password: <TextField ref={newpassword} label="new password" type="password" /></p>
        <p>new password: <TextField ref={againpassword} label="new password again" type="password" /></p>
        <button onClick={handlePasswordChange}>submit</button>
    </>
    )
}

我想获取ref TextField的值,但未定义。 如何获取ref TextField的值?

我已阅读以下答案: React: How to get values from Material-UI TextField components

但是对于表单按钮的答案,如果我没有表单怎么办?

1 个答案:

答案 0 :(得分:0)

您需要使用inputRef而不是ref
这是因为inputRef会将ref传递给输入元素。

const UserDetail = (props: ListDetailProps) => {
    const oldpassword = useRef<TextFieldProps>(null);
    const newpassword = useRef<TextFieldProps>(null);
    const againpassword = useRef<TextFieldProps>(null);
    const handlePasswordChange = async () => {
        console.log(newpassword.current?.value)    //expect the password value but undefined get
        console.log(againpassword.current?.value)  //expect the password value but undefined get
    }
    return (<>
        <p>old password: <TextField inputRef={oldpassword} label="old password" type="password" /></p>
        <p>new password: <TextField inputRef={newpassword} label="new password" type="password" /></p>
        <p>new password: <TextField inputRef={againpassword} label="new password again" type="password" /></p>
        <button onClick={handlePasswordChange}>submit</button>
    </>
    )
}

您可以参考material-ui TextField API docs