设置onClick通过document.createelement生成的动态元素

时间:2017-03-15 18:38:26

标签: javascript reactjs

我正在尝试设置动态生成元素的onClick函数。该函数必须设置状态。

var root = document.getElementById("results_container");
var title = document.createElement('a'); 
title.setAttribute("id", 'title');
title.onclick = function () {
    this.setState({
        isOpen: !this.state.isOpen
    });
}.bind(this)

我收到了Uncaught TypeError:无法读取属性' state'未定义的,我假设onclick函数无法到达this.state。请帮忙

2 个答案:

答案 0 :(得分:0)

您可以使用jQuery函数on。即使在新生成的元素中,它也会绑定动作。

$(document).on('click', '#test', function() {
    // statement here
})

供参考:jQuery .on()

答案 1 :(得分:0)

您的this变量未定义...如果您正在使用react,则需要将对组件实例(this)的引用存储在某处,并将其传递给bind函数。然而,这可能是一种非常糟糕的方式。如果你正在使用反应,你可能想要更像这样的东西:

class Results extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isOpen: false
    };
  }
  render() {
    return <div>
      <a onClick={()=>this.setState({isOpen:!this.state.isOpen})}>
        Title  
      </a>
      {this.state.isOpen ? this.getOpenContent() : null}
    </div>;
  }
  getOpenContent() {
    return <div> ... </div>;
  } 
}
相关问题