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

use*_*909 3 typescript reactjs 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>
    </>
    )
}
Run Code Online (Sandbox Code Playgroud)

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

我已阅读以下答案: React:如何从 Material-UI TextField 组件中获取值

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

Ido*_*Ido 7

您需要使用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>
    </>
    )
}
Run Code Online (Sandbox Code Playgroud)

您可以参考material-ui TextField API文档