如何在Slate.js的onChange/onKeyDown中获取当前行或编辑节点?
在Slate.js的onChange/onKeyDown中获取当前编辑行并添加时间戳
嘿,我来帮你搞定这个问题!你想在onChange或者onKeyDown里拿到当前正在编辑的行(节点),还想给特定行添加createdAt和updatedAt时间戳对吧?其实不用遍历所有节点,咱们可以精准定位到当前编辑的节点,这样效率更高,也能实现你要的效果。
一、如何获取当前编辑的节点(当前行)
不管是在onChange还是onKeyDown方法里,你都可以通过value.selection来定位当前光标/选区所在的位置,再通过Slate提供的方法拿到对应的块级节点(也就是你说的“行”):
const { selection } = value; // 如果是光标定位的状态(*collapsed* 选区),取起始位置的节点key const currentBlockKey = selection.start.key; // 获取当前节点所在的最外层块级节点(就是当前行) const currentBlock = value.document.getClosestBlock(currentBlockKey);
如果是选中了多行内容的情况,你可以根据需求判断处理,但一般单行编辑场景下,这段代码就能精准拿到当前行的节点。
二、修改你的代码,实现只更新当前行的时间戳
你之前的代码会遍历所有节点并更新时间戳,这会把每一行的时间都改掉,显然不是你想要的。咱们调整一下,只给当前正在编辑的行更新时间:
onChange = ({ value }) => { const { selection } = value; // 如果是多选状态,这里可以根据需求处理,或者直接返回原value if (!selection.isCollapsed) { return value; } const currentBlockKey = selection.start.key; const currentBlock = value.document.getClosestBlock(currentBlockKey); // 防止找不到节点的情况 if (!currentBlock) return value; // 只更新当前行的data属性 return value.change() .setNodeByKey(currentBlockKey, { data: { // 第一次创建时设置createdAt,之后保留原有的值不覆盖 createdAt: currentBlock.getIn(['data', 'createdAt']) || new Date(), // 每次编辑都更新updatedAt updatedAt: new Date(), // 保留原来的data内容 ...currentBlock.get('data').toJS(), }, }) .value; };
这样每次编辑的时候,只有当前正在修改的行会更新updatedAt,而createdAt只会在该行第一次被创建的时候设置,不会被后续修改覆盖。
三、在onKeyDown中获取当前行的方法
如果是在onKeyDown事件里,逻辑是完全一样的,因为你可以从editor对象中拿到value:
onKeyDown = (event, editor, next) => { const { value } = editor; const { selection } = value; const currentBlockKey = selection.start.key; const currentBlock = value.document.getClosestBlock(currentBlockKey); // 举个例子:按下回车时打印当前行信息 if (event.key === 'Enter') { console.log('当前编辑的行:', currentBlock.toJS()); } // 别忘了调用next()让其他key事件正常触发 return next(); };
内容的提问来源于stack exchange,提问作者thekevinscott
相关产品推荐
相关产品推荐

