选择标题标记时删除粗体和斜体格式



我正在用React构建一个文本编辑器,遇到了一个小问题。当我选择一个h1标记并单击"B"one_answers"I"时,它仍在格式化。如果选择的文本是h1,我需要以某种方式防止它,或者根本不允许格式化。

按钮组件:

class Btn extends Component {
constructor(){
super();
this.clicked = false;
}
onClick = e => {
if(this.clicked && this.props.cmd === 'heading'){
document.execCommand('formatBlock', false, 'p');
} else {
document.execCommand('formatBlock', false, this.props.arg);
document.execCommand(this.props.cmd, false, this.props.arg);
}
this.clicked = !this.clicked;
}
render(){
return <button onClick={this.onClick} id={this.props.id}><li className={"fas fa-" + this.props.name}></li></button>;
}

演示:https://codesandbox.io/s/vyr6344ljl

您对问题的标题和描述使您很难确定想要什么。

但是,您将状态存储在实例变量中,而不是使用Reactstate变量。

虽然我不确定你遇到的错误到底是什么,但我可以建议你尝试以下方法:

class Btn extends Component {
constructor(){
super();
this.state = { clicked: false };
}
onClick = e => {
if(this.state.clicked && this.props.cmd === 'heading'){
document.execCommand('formatBlock', false, 'p');
} else {
document.execCommand('formatBlock', false, this.props.arg);
document.execCommand(this.props.cmd, false, this.props.arg);
}
this.setState((state, props) => ({clicked: !state.clicked}));
}
render(){
return <button onClick={this.onClick} id={this.props.id}><li className={"fas fa-" + this.props.name}></li></button>;
}

最新更新