我需要从Material-ui的TextField获取文本选择数据。文本选择数据必须包括选择开始,选择结束和选择的文本。
我设法使用createRefs达到以下内容
import React, { createRef } from "react";
import { TextField, Button, Box, Grid } from "@material-ui/core";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
selStart: undefined,
selEnd: undefined,
selValue: undefined
};
this.onSaveSelectionClicked = this.onSaveSelectionClicked.bind(this);
this.textFieldRef = createRef();
}
onSaveSelectionClicked(ev) {
// Somehow obtain selection start, end, and value
// then update state
const { selectionStart, selectionEnd, value } = this.textFieldRef.current;
this.setState({
selStart: selectionStart,
selEnd: selectionEnd,
selValue: value.substring(selectionStart, selectionEnd)
});
}
render() {
return (
<Box p="2em">
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
name="essay1"
label="Essay 1"
multiline
rows={3}
fullWidth
inputRef={this.textFieldRef}
/>
</Grid>
<Grid item xs={12}>
<TextField
name="essay2"
label="Essay 2"
multiline
rows={3}
fullWidth
inputRef={this.textFieldRef}
/>
</Grid>
<Grid item xs={12}>
<Button variant="contained" onClick={this.onSaveSelectionClicked}>
Save selection
</Button>
</Grid>
<Grid item xs={12}>
<pre>{JSON.stringify(this.state)}</pre>
</Grid>
</Grid>
</Box>
);
}
}
这给了我以下
问题是,这似乎不适用于多个TextField。current
裁判的属性将始终引用“论文2”文本字段。
有没有更好的方法来解决此问题?
这是上述代码的codeandbox的链接
完全不需要引用,因此选择会动态更改。
更改构造函数,如下所示:
constructor(props) {
super(props);
this.state = {
selStart: undefined,
selEnd: undefined,
selValue: undefined
};
this.onSelectionChange = this.onSelectionChange.bind(this);
}
添加处理程序:
onSelectionChange(e) {
const { selectionStart, selectionEnd, value } = e.target;
this.setState({
selStart: selectionStart,
selEnd: selectionEnd,
selValue: value.substring(selectionStart, selectionEnd)
});
}
然后在您的文本字段中,只需将事件设置为onMouseUp(或onBlur,如果您想更新lostFocus):
onMouseUp={this.onSelectionChange}
这样做,您的源代码如下:
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
selStart: undefined,
selEnd: undefined,
selValue: undefined
};
this.onSelectionChange = this.onSelectionChange.bind(this);
}
onSelectionChange(e) {
const { selectionStart, selectionEnd, value } = e.target;
this.setState({
selStart: selectionStart,
selEnd: selectionEnd,
selValue: value.substring(selectionStart, selectionEnd)
});
}
render() {
return (
<Box p="2em">
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
name="essay1"
label="Essay 1"
multiline
rows={3}
fullWidth
onMouseUp={this.onSelectionChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
name="essay2"
label="Essay 2"
multiline
rows={3}
fullWidth
onMouseUp={this.onSelectionChange}
/>
</Grid>
</Grid>
</Box>
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句