我尝试使用this.refs.myField.getValue()
或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;
答案 0 :(得分:1)
您正在尝试访问文本区域的基础值,因此需要HTML DOM元素的引用。
对于文本区域,使用:
<TextField
inputRef={ref => { this.inputRef = ref; }}
fullWidth
/>
然后在您的方法中使用this.inputRef.value
访问该值。
答案 1 :(得分:0)
const { register, handleSubmit } = useForm();
<form onSubmit={handleSubmit(formSubmit)}>
<label>
<TextField
id="outlined-basic"
label="email"
name="email"
fullWidth
variant="outlined"
inputRef={register}
required
/>
</label>
<br />
<label>
<br />
<TextField
id="outlined-secondary:cyan"
label="password"
name="password"
type="password"
fullWidth
variant="outlined"
inputRef={register}
required
/>
</label>
<br />
<br />
<Button
className={classes.root}
variant="contained"
color="primary"
fullWidth
type="submit"
>
Login
</Button>
</form>
然后使用:
const formSubmit = (data) => {
// Post Data
const postData = {
email: data.email,
pass: data.password,
};
console.log(data)