【问题标题】:How can I clear the the inner text of a ref.current value, in React?如何在 React 中清除 ref.current 值的内部文本?
【发布时间】:2021-10-20 14:41:41
【问题描述】:

如何访问 ref.current 的内部文本值属性。

通过 console.log(loginField.current) 我得到了:

<div class="some name">
   <input aria-invalid="false" id="login" placeholder="Email" type="text" class="other name" value="">
</div>

我设置loginField的方式是:

  let loginField = React.createRef();

          <FormControl className={clsx(classes.margin, classes.textField)}>
            <StyledInput
              id={LOGIN}
              type="text"
              value={values.login}
              disableUnderline={true}
              placeholder="Email"
              ref={loginField}             // I set it here
              onFocus={handleFocus}
              error={fieldsErrors.loginError !== ''}
              onChange={handleChange(LOGIN)}
            />
          </FormControl>

我需要从以前的值中清除此 div 的内部输入。 (将其设置为 '')

提前致谢

拉斐尔

【问题讨论】:

  • 感谢您的回答,我尝试了 loginField.current.reset(),但出现错误,说“loginField.current.reset 不是函数”。我也直接在对字段的引用中尝试了 reset(),但我也得到了一个错误

标签: reactjs material-ui ref form-control create-ref


【解决方案1】:

既然您提到您正在使用 MUI,它基本上根据文档 here 提供了一个包装的组件,并且要将参考传递给输入,您必须将一个 prop 传递给组件作为

   ...
   inputRef={myref}
   ...

【讨论】:

  • 嗨@Fahad Tahir,我尝试了所有方法都没有成功。通过执行 console.log 我发现我的 ref 值类似于“
    ”,它是 html,而不是对象(我想那是因为我正在使用Material UI 的 FormControl),它是一个 div 包围了一个输入,输入有一个值。如何获取该输入以设置其值?清除状态并不是在页面首次呈现时清除值。但是,它工作得很好
  • 你能分享你在哪里做样式的 StyledInput
  • 试试这个``` const StyledButton = styled.button` min-width: 200px;字体大小:18px;填充:7px 10px; ; const StyledInput = styled.input最小宽度:200px;字体大小:18px;填充:7px 10px; `; function Profile() { let inputRef = useRef() const handleClear = () => { console.log(inputRef.current.value) inputRef.current.value = "" } return (
    clear
    ) } ``
  • 我没有直接使用样式化组件,我使用的是 Material UI,我定义 StyledInput 的方式是:“const StyledInput = withStyles({ root: { '&$focused': { borderColor: ' #B3B3B3' }, '&$error': {borderColor: '#D33F49' }, ... })(Input);", 这个“withStyles”是从'@material-ui/core/styles'导入的
  • 我没看懂你写的定义
猜你喜欢
  • 2020-02-19
  • 2011-12-08
  • 1970-01-01
  • 2022-11-04
  • 2018-08-01
  • 2018-02-13
  • 1970-01-01
  • 2011-06-16
  • 2014-04-30
相关资源
最近更新 更多