React ref:什么等于document.querySelectorAll

时间:2018-07-30 16:44:32

标签: reactjs ref

我刚开始使用React refs,我想选择ref = this.contentRef的所有图标。 使用js,我会这样:document.querySelectorAll('。content i')。如何使用裁判?

someMethode() {
  const content = this.contentRef.current.childNodes;
  const content2 = document.querySelectorAll('.content i');
}

render() {
  return (
    <div ref={this.contentRef} className="content">
      <div>
        <i className="fa fa-square" />
      </div>
      <div>
        <i className="fa fa-square" />
      </div>
      <div>
        <i className="fa fa-square" />
      </div>
    </div>
  )
}

2 个答案:

答案 0 :(得分:0)

正确的方法是:

 <MyComponent ref={(c) => this.myComponent = c} /> // then check when this.myComponent is NOT undefined 

问题出在您想对引用进行的处理上。当为所有其余情况调用子方法或进行计算(渲染大小等)时,它非常有用,在没有引用的情况下,还有其他模式可以完成工作

答案 1 :(得分:0)

您实际上可以将QuerySelectorall与ReactDOM.findDOMNode(this)一起使用 尝试像这样

const node = ReactDOM.findDOMNode(this);
// Get child nodes
if (node instanceof HTMLElement) {
const child = node.querySelector('.someClass');
}