reactjs - innerHTML 返回旧值而不是新值
问题描述
我有一个内容可编辑的 div 和一个附加到按钮并在单击时触发的事件。
当它被触发时,它会写入innerHTML
该 div,但我不知道为什么使用旧值。
class Btn extends React.Component {
constructor(){
super();
this.state = { clicked: false };
}
onClick = e => {
console.log(document.getElementById('typer').toString());
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}>btn</button>;
}
}
const root = document.querySelector('#app');
ReactDOM.render(
<div>
<nav>
<Btn cmd="bold" name="bold"/>
<Btn cmd="italic" name="italic"/>
<Btn id="big" cmd="heading" name="heading" arg="H1"/>
<Btn id="sml" cmd="heading" name="heading" arg="H2"/>
</nav>
<TyperArea/>
</div>, root
)
nav{text-align:center;border-bottom:2px solid black;top:0;position:sticky;width:100%;background:white}button{vertical-align:middle;display:inline-block;font-size:25px;border-style:none;padding:6px;margin:0 10px;background-color:white;cursor:pointer}button:hover{color:darkslategrey}body{margin:0;width:100%}div[contentEditable=true]{height:10em;width:700px;padding:20px;outline:none;font-family:Georgia;margin:0 auto;font-size:27px}h1,h2{font-family:arial;font-weight:bold}h1{font-size:42px}h2{font-size:35px}#sml{font-size:26px}#big{font-size:30px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
解决方案
绑定是使“this”在回调中工作所必需的
constructor(){
super();
this.state = { clicked: false };
this.onClick = this.onClick.bind(this);
}
推荐阅读
- postgresql - 为什么我在初始化 gitlab 数据库 - postgresql 期间无法进行身份验证?
- windows - 在 Windows 上通过 docker 安装 Clickhouse 的主机上的数据目录权限
- c++ - 在 C++ 中获取有符号整数乘法的高部分
- python-3.x - 如何从数据集中替换问号符号并替换为相邻行值?
- twilio - 使用 SSML 时 Twilio Autopilot 崩溃?
- java - 带有 gradle 的 IntelliJ 导致编译不一致
- python - 非默认参数遵循默认参数
- javascript - 如何为在 ng-repeat 中循环的每个 md-chip 应用样式:AngularJS
- amazon-web-services - 我需要什么权限才能在两个不同帐户的两个存储桶之间复制对象?
- amazon-cloudformation - CloudFormation 是否可以通过模板创建 PipeLine 手动审批操作?