首页 > 解决方案 > 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>

标签: reactjs

解决方案


绑定是使“this”在回调中工作所必需的

constructor(){
    super();
    this.state = { clicked: false };
    this.onClick = this.onClick.bind(this);
}

阅读更多


推荐阅读