为了实现这个功能,我们需要对现有的代码进行一些修改。主要的思路是:
- 在每个段落的右侧添加一个编辑按钮。
- 当鼠标悬停在段落上时,显示编辑按钮。
- 点击编辑按钮进入编辑状态。
- 点击任何空白的地方退出编辑状态。
下面是具体的修改步骤:
1. 修改 EditableBlock 组件
首先,我们需要在 EditableBlock 组件中添加一个编辑按钮,并控制其显示和隐藏。
jsx
const EditableBlock = ({ attributes, children, element, index, editableIndex, setEditableIndex }) => {
const editor = useSlateStatic();
const path = ReactEditor.findPath(editor, element);
const type = element.type;
const allowedChild = getNextHeadingType(type);
const [isHover, setIsHover] = useState(false);
const handleMouseEnter = () => {
setIsHover(true);
};
const handleMouseLeave = () => {
setIsHover(false);
};
const handleEditClick = () => {
setEditableIndex(index);
};
const tagMap = {
'heading-one': 'h1',
'heading-two': 'h2',
'heading-three': 'h3',
'heading-four': 'h4',
paragraph: 'p',
};
const Tag = tagMap[type] || 'p';
return (
<div
className={`block-wrapper ${editableIndex === index ? 'active' : ''}`}
{...attributes}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<Tag
className="editable-block"
contentEditable={editableIndex === index}
suppressContentEditableWarning={true}
>
{children}
</Tag>
{isHover && (
<div className="edit-button" onClick={handleEditClick}>
编辑
</div>
)}
{editableIndex === index && (
<div className="block-buttons">
<button onClick={() => insertNode(type)} title="添加同级">➕</button>
<button
onClick={() => allowedChild && insertNode(allowedChild)}
disabled={!allowedChild}
title={allowedChild ? '添加子级' : '不可添加子级'}
>📎</button>
<button onClick={removeNode} title="删除">🗑</button>
</div>
)}
</div>
);
};
2. 添加 CSS 样式
我们需要添加一些 CSS 样式来控制编辑按钮的显示和隐藏。
css
.edit-button {
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
background-color: #f0f0f0;
border: 1px solid #ddd;
padding: 5px 10px;
cursor: pointer;
}
.edit-button:hover {
background-color: #e0e0e0;
}
.block-wrapper {
position: relative;
}
.block-buttons {
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
}
3. 修改 StepIII 组件
我们需要修改 StepIII 组件来处理点击任何空白的地方退出编辑状态。
jsx
const StepIII = () => {
const [editableIndex, setEditableIndex] = useState(null);
const handleDocumentClick = (e) => {
if (!e.target.closest('.block-wrapper')) {
setEditableIndex(null);
}
};
useEffect(() => {
document.addEventListener('click', handleDocumentClick);
return () => document.removeEventListener('click', handleDocumentClick);
}, []);
// ...
};
通过这些修改,我们可以实现直接将编辑按钮添加在右侧,当鼠标的聚焦于对应段落时,对应段落右侧会出现按钮,点击按钮进入编辑状态,点击任何空白的地方即可退出编辑状态。