【发布时间】:2019-09-16 18:45:33
【问题描述】:
目前
- 我有一个反应组件,当用户单击 contentEditable
<div>时存储一个newValue,并在用户键入时更新newValue。 注意:我以这种方式设置此行为的主要原因有两个:(1)我不想在每次击键时发送要保存的数据,以及(2)我计划使用这个 div 检查每个输入以验证输入是否为数字。 -
<div>失去焦点时发送newValue保存,然后重置道具状态。
问题
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>) - 我已经能够找到许多相关的答案,但没有一个是特定于反应的,例如Maintain cursor position in contenteditable div。我认为因为 react 会在每次笔划后重新加载组件,所以会出现这个问题。
- 我以前没有 ChangeHandler onInput,这工作正常,但我无法记录每次按键并验证字符是否为数字。
【问题讨论】:
-
为你的组件制作一个 FiddleJS,我会帮你调试
-
我实际上一开始尝试制作一个 Fiddlejs,但未能使其正常工作。据我所知:jsfiddle.net/e4utgwc1。我不确定如何处理 react 和 react-dom 模块。
标签: javascript html reactjs