当前
newValue
时存储一个<div>
,并在用户键入时更新newValue
。 注意:之所以以这种方式设置此行为,主要有两个原因:(1)我不想发送要在每次击键时保存的数据,并且(2)我计划使用以下形式此div,将检查每个输入以验证输入是否为数字。 newValue
失去焦点后,<div>
被发送以保存,然后重置道具的状态。问题
onChangeHandler
正在将插入标记在可编辑div中的位置移到左侧。这导致按键123456
显示为654321
代码:
class Input extends Component {
constructor(props) {
super(props);
this.state = {
//newValue input by user
newValue : undefined
}
}
//handler during key press / input
onChangeHandler = event => {
let targetValue = event.currentTarget.textContent;
this.setState({"newValue": targetValue})
}
//handler when user opens input form
onBlurHandler = event => {
//some code that sends the "newValue" to be saved, and resets state
}
render() {
//determine which value to show in the div
let showValue;
//if there is a new value being input by user, show this value
if (this.state.newValue !== undefined) {
showValue = this.state.newValue;
} else {
//if prop has no value e.g. null or undefined, use "" placeholder
if (this.props.value) {
showValue = this.props.value;
} else {
showValue = "";
}
}
return (
<table>
<tbody>
<td>
<div
contentEditable="true"
suppressContentEditableWarning="true"
onInput={this.onChangeHandler.bind(this)}
onBlur={this.onBlurHandler}
>{showValue}
</div>
</td>
</tbody>
</table>
)
}
}
export default Input;
注释
<textarea>
来完成此操作的,但没有这个问题,但是切换到<div>
可以更好地控制自动调整div高度的行为(参考CSS: Remove scroll bar and replace with variable height for textarea in a table <td>)< / li>
答案 0 :(得分:1)
ContentEditable是一个棘手的问题,特别是在做出反应时,因为您必须考虑许多不同种类的行为。我可以建议您看看Facebook的DraftJS。
他们采用contentEditable并阻止了所有默认行为,并建立了一个不错的框架来使标签可编辑,他们将其用于富文本编辑器,但是您可以使用相同的框架而不必费吹灰之力就可以控制内容可编辑的。
答案 1 :(得分:0)
我能够在https://stackoverflow.com/a/13950376/1730260
中获得以下解决方案主要更改:
EditCaretPositioning.js
:(1)saveSelection保存插入符位置,(2)restoreSelection恢复插入符位置。Input
组件状态saveSelection()
restoreSelection()
作为回调id
中添加了<div>
,因此可以在restoreSelection()
函数中引用EditCaretPositioning.js
const EditCaretPositioning = {}
export default EditCaretPositioning;
if (window.getSelection && document.createRange) {
//saves caret position(s)
EditCaretPositioning.saveSelection = function(containerEl) {
var range = window.getSelection().getRangeAt(0);
var preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(containerEl);
preSelectionRange.setEnd(range.startContainer, range.startOffset);
var start = preSelectionRange.toString().length;
return {
start: start,
end: start + range.toString().length
}
};
//restores caret position(s)
EditCaretPositioning.restoreSelection = function(containerEl, savedSel) {
var charIndex = 0, range = document.createRange();
range.setStart(containerEl, 0);
range.collapse(true);
var nodeStack = [containerEl], node, foundStart = false, stop = false;
while (!stop && (node = nodeStack.pop())) {
if (node.nodeType === 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
range.setStart(node, savedSel.start - charIndex);
foundStart = true;
}
if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
range.setEnd(node, savedSel.end - charIndex);
stop = true;
}
charIndex = nextCharIndex;
} else {
var i = node.childNodes.length;
while (i--) {
nodeStack.push(node.childNodes[i]);
}
}
}
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
} else if (document.selection && document.body.createTextRange) {
//saves caret position(s)
EditCaretPositioning.saveSelection = function(containerEl) {
var selectedTextRange = document.selection.createRange();
var preSelectionTextRange = document.body.createTextRange();
preSelectionTextRange.moveToElementText(containerEl);
preSelectionTextRange.setEndPoint("EndToStart", selectedTextRange);
var start = preSelectionTextRange.text.length;
return {
start: start,
end: start + selectedTextRange.text.length
}
};
//restores caret position(s)
EditCaretPositioning.restoreSelection = function(containerEl, savedSel) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(containerEl);
textRange.collapse(true);
textRange.moveEnd("character", savedSel.end);
textRange.moveStart("character", savedSel.start);
textRange.select();
};
}
更新后的contentEditable div组件:
import CaretPositioning from 'EditCaretPositioning'
class Input extends Component {
constructor(props) {
super(props);
this.state = {
//newValue input by user
newValue : undefined,
//stores positions(s) of caret to handle reload after onChange end
caretPosition : {
start : 0,
end : 0
}
}
}
//handler during key press / input
onChangeHandler = event => {
let targetValue = event.currentTarget.textContent;
//save caret position(s), so can restore when component reloads
let savedCaretPosition = CaretPositioning.saveSelection(event.currentTarget);
this.setState({
"newValue": targetValue,
"caretPosition" : savedCaretPosition
}, () => {
//restore caret position(s)
CaretPositioning.restoreSelection(document.getElementById("editable"), this.state.caretPosition);
})
}
//handler when user opens input form
onBlurHandler = event => {
//some code that sends the "newValue" to be saved, and resets state
}
render() {
//determine which value to show in the div
let showValue;
//if there is a new value being input by user, show this value
if (this.state.newValue !== undefined) {
showValue = this.state.newValue;
} else {
//if prop has no value e.g. null or undefined, use "" placeholder
if (this.props.value) {
showValue = this.props.value;
} else {
showValue = "";
}
}
return (
<table>
<tbody>
<td>
<div
id="editable"
contentEditable="true"
suppressContentEditableWarning="true"
onInput={this.onChangeHandler.bind(this)}
onBlur={this.onBlurHandler}
>{showValue}
</div>
</td>
</tbody>
</table>
)
}
}
export default Input;
答案 2 :(得分:0)
在尝试在<td>
上可编辑的内容时,我也遇到了这个问题。编辑时光标移到开始处,我尝试了多种方法,但无济于事!
后来,我最终使用了这个“内容可编辑”的React包。
https://github.com/lovasoa/react-contenteditable
以前,我使用的代码是这样的
<td
onInput={(e) =>this.handleInput(e, user, "name", index)}
contentEditable={user.isEditable}
className={
user.isEditable ? "border border-success" : ""
}
>
{user.name}
</td>
包含软件包后,我使用以下代码对其进行了更改。现在它可以正常工作了。
<td className={user.isEditable ? "border border-success" : ""}>
<ContentEditable
html={user.name}
disabled={!user.isEditable}
onChange={(e) =>
this.handleInput(e, user, "name", index)
}
style={{ "text-decoration": "none" }}
/>
</td>