如何访问 MaterialUI/React 中的 inputRef 值
我想类似地访问DOM元素以与USEREF访问GetElementByD。我像这样声明了我的变量,这是我的texfield:
const inputRefAmount = useRef<HTMLInputElement>(null);
<TextField
inputRef={inputRefAmount}
value={amount}
id="output_elevator-amount"
label="Elevator amount"
color='primary'
type="number"
InputLabelProps={{
shrink: true,
}}
InputProps={{
readOnly: true,
}}
onChange={serviceCalc}
/>
<TextField
在一个我想使用ref操纵的功能中,类似的东西(不起作用)
const standard = () => {
console.log("returns standard")
let elevatorAmt = inputRefAmount.current
console.log(elevatorAmt)
let unitPrice = 7565;
let installFee = (unitPrice * parseInt(elevatorAmt.value)) * 0.1;
谢谢您的帮助
I want to access DOM elements similarly to getElementById with useRef. I declare my variable like so and this is my Texfield:
const inputRefAmount = useRef<HTMLInputElement>(null);
<TextField
inputRef={inputRefAmount}
value={amount}
id="output_elevator-amount"
label="Elevator amount"
color='primary'
type="number"
InputLabelProps={{
shrink: true,
}}
InputProps={{
readOnly: true,
}}
onChange={serviceCalc}
/>
<TextField
In a function I would like to use the ref to manipulate it, something like this(which does not work)
const standard = () => {
console.log("returns standard")
let elevatorAmt = inputRefAmount.current
console.log(elevatorAmt)
let unitPrice = 7565;
let installFee = (unitPrice * parseInt(elevatorAmt.value)) * 0.1;
thank you for your help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据提供的代码,您似乎正在使用ref接收
textfield
而不是操纵它的值。如果您需要价值,则应使用
金额
状态。这是根据React :
这是 又有有关useffect&amp&amp&amp; Uselayouteffect,几乎总是在Useref上使用的钩子。
According to the provided code, it seems you are using ref to receive the value of
TextField
rather than manipulate it.In case you need to value, you should use your
amount
state.Here are some use cases for refs according to React docs:
Here's another good read about useEffect & useLayoutEffect, hooks that are used along useRef almost always.