【问题标题】:How to get TextField(Material-UI) value from hook react component?如何从钩子反应组件中获取 TextField(Material-UI) 值?
【发布时间】:2020-12-20 15:13:31
【问题描述】:

我使用 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,

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-29
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      相关资源
      最近更新 更多