1

我将 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

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

4

1 回答 1

2

您需要使用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

于 2020-09-01T15:00:19.263 回答