首页 > 解决方案 > 如何在不使用 onChange 事件的情况下从 Material UI 获取 TextField 的输入值?

问题描述

我尝试使用this.refs.myField.getValue()or this.refs.myTextField.input.value。但是,它们是贬值的。

我不想在onChange里面使用TextField,我只是在单击按钮转换时转换文本

import React from 'react';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';

class Test extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      text: '',
    };
  };

  handleConvertString = (event) => {
    let str = this.refs.myField.getValue();
    this.setState({
      text: str.replace(/[dog]/gi, ''),
    })
  };
  render() {
    return (
      <div>
        <TextField
          ref="myField"
          fullWidth
        />
        <Button variant="outlined" href="#outlined-buttons" onClick={this.handleConvertString}>
          Convert
        </Button>
        <h1>{this.state.text}</h1>
      </div>
    )
    }
}

export default Test;

标签: reactjsmaterial-uireact-router-dom

解决方案


查看MUI 文本字段 API 文档

您正在尝试访问文本区域的基础值,因此您需要 HTML DOM 元素的 ref。

对于文本区域,使用:

<TextField
  inputRef={ref => { this.inputRef = ref; }}
  fullWidth
/>

然后在您的方法中使用this.inputRef.value.


推荐阅读