reactjs - 如何在不使用 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;
解决方案
您正在尝试访问文本区域的基础值,因此您需要 HTML DOM 元素的 ref。
对于文本区域,使用:
<TextField
inputRef={ref => { this.inputRef = ref; }}
fullWidth
/>
然后在您的方法中使用this.inputRef.value
.
推荐阅读
- tensorflow - 我想了解用于创建 tensorflow 应用程序的 TensorFlowInferenceInterface。哪些来源可以信任?
- google-maps - 当汽车移动时如何更新(不增长)折线 - 谷歌地图?
- php - 当一个人登录时,我如何隐藏某些表单,如登录表单?
- javascript - Mongoose 不在生产(Heroku)上填充(.populate()),但在本地工作
- php - 通过匹配键将数组中的新项添加到组合数组中
- android - onClick() 内部的意图
- macos - 以“Linux”方式使 macOS 应用程序可编写脚本
- dart - 使用异步创建类
- javascript - Dojo ConfirmDialog 隐藏取消按钮
- python - 释放python中所有使用的内存