【问题标题】:Parsing element on clicking a button单击按钮时解析元素
【发布时间】:2018-09-12 11:56:32
【问题描述】:

所以我想在单击“选择”按钮后解析 h2 标记并将其文本内容保存到常量中

<div className={"card " + (this.state.selected ? "methodSelected" : "")}>
    <h2 className="charge"></h2>
    <button onClick={this.selectMethod} href="#"className="btn return-btn">SELECT</button>
</div>

点击按钮后我用来设置状态的函数

selectMethod = () => {
      this.setState({selected: true});
  }

【问题讨论】:

  • 你能展示一下吗,你试过什么?这样我们就可以从那里开始讨论了……

标签: reactjs ecmascript-6 react-props


【解决方案1】:

在 selectMethod 方法中你可以添加 -

selectMethod = () => {
  this.setState({selected: true});
  let x = document.getElementByClassName("charge").textContent;
  // doing something with the variable 'x'

}

【讨论】:

    【解决方案2】:

    根据我对问题的理解,这可以通过以下方式完成

    selectMethod = () => {
          document.getElementById('heading').innerHTML="sample text"
          this.setState({selected: true});
      }
    

    还将id 属性添加到标题标签中

    <h2 id="heading"></h2>
    

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 2019-05-19
      • 2020-12-08
      • 1970-01-01
      相关资源
      最近更新 更多