我正在使用 React 构建一个文本编辑器,但遇到了一个小问题。当我选择 h1 标签并单击“B”和“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>;
}
最佳答案
您的问题标题和描述使您很难确定您想要什么。
但是,您将状态存储在实例变量中,而不是使用 React state
变量。
虽然我不确定您遇到的错误到底是什么,但我可以建议您尝试以下操作:
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>;
}
关于javascript - 选择标题标签时删除粗体和斜体格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53035141/