gpt4 book ai didi

reactjs - 如何从钩子(Hook) react 组件中获取 TextField(Material-UI) 值?

转载 作者:行者123 更新时间:2023-12-02 16:30:02 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于reactjs - 如何从钩子(Hook) react 组件中获取 TextField(Material-UI) 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63688785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com