繁体   English   中英

React,如何从同一个组件访问我的渲染函数中的 DOM 元素

[英]React, how to access the DOM element in my render function from the same component

我想知道从同一组件访问渲染函数中的 DOM 元素的最佳实践是什么。 请注意,我将在页面上多次渲染此组件。

例如

var TodoItem = React.createClass({
    ...
    render:function(){

        function oneSecLater(){
            setTimeout(function(){
            //select the current className? this doesn't work, but it gives you an idea what I want.
            document.getElementsByClassName('name').style.backgroundColor = "red";
                )}, 1000);
        }

        return(
            <div className='name'>{this.oneSecLater}</div>
        )



})

您可以使用ReactDOM.findDOMNode(this)来访问底层DOM节点。 但访问DOM节点并像操作一样操作是违反React编程风格的。 最好使用状态变量并调用setState方法来重新呈现DOM。

在这里,不需要使用setTimeout。 组件有生命周期方法,在渲染后调用componentDidMount 因此,您可以在方法中获得对div的引用。

var TodoItem = React.createClass({
  ...
  componentDidMount: function () {
     if(this.myDiv) {
        this.myDiv.style.backgroundColor = "red";
     }
  }
  render:function(){
    return(
        <div className='name' ref = {c => this.myDiv = c}></div>
    );
});

您可以使用ref callback来访问react中的dom元素,这是React Docs建议遵循的内容

并在componentDidMount生命周期函数中执行此操作,因为在创建DOM之前将无法访问refs

var TodoItem = React.createClass({
    ...
    componentDidMount() {
          setTimeout(function(){
               this.myDiv.style.backgroundColor = "red";
          )}, 1000);
    }
    render:function(){

        return(
            <div className='name' ref={(ele) => this.myDiv = ele}></div>
        )

})

DOCS

这是我的解决方案:要获取特定元素的computedCss,您需要首先向elemenet添加ref属性。

在此输入图像描述

render(){
  <div>
    <Row className="chartline2">
      <Col className="gutter-row" span={24}>
        <div className="gutter-box lineChartWrap" id="lineChartWrap" ref="lineChartWrap">
            <LineChart data={lineChartData} options={lineChartOptions} width="100%" height="300"/>
        </div>
      </Col>
    </Row>
  </div>
}

然后,在componentDidUpdate()函数中,使用window.getComputedStyle(this.refs.lineChartWrap)获取元素的css .XXX 在此处输入图像描述

  componentDidUpdate(){ console.log("------- get width ---"); let ele = document.querySelector("#lineCharWrap"); console.log(this.refs.lineChartWrap); console.log(window.getComputedStyle(this.refs.lineChartWrap).width); } 

你应该避免访问DOM元素,因为反应的重点是将抽象放在dom上。 React将DOM表示在内存中,称为VirtualDom。 使用VirtualDom将使您的应用程序的单元测试更容易。如果您真的知道自己在做什么,请按以下步骤操作:

componentDidMount(){
const name=this.name.current.style() //current will return the actual DOM 
element
}
name=React.createRef()  //create a ref object

<div ref={this.name} className="anything" /> //your classname does not need to be named as "name". You access the element via the "ref" attribute not the classname.

在ComponentDidMount中,当您的组件被挂载时,将应用其样式更改。

刚刚在使用React 14打开条纹结帐模式之前尝试进行表单验证后遇到了这个问题。

我想请注意,您实际上并没有使用引用来访问DOM元素。 您只是访问React组件对象。 如图所示:

在此输入图像描述

最上面一个是调用ref.ticketForm ,底部是显示document.getElementById('ticketform')

我需要这样做的原因如下:

<Button color="success" size="lg" type="button" onClick={(e) => {
  const ticketForm = document.getElementById('ticketForm');
  const isValid = ticketForm.reportValidity();
  if (!isValid) e.stopPropagation();
}}>Buy Tickets</Button>

reportValidity()是一个DOM元素方法: https//developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reportValidity

引用此问题,此人显示此方法用于引用对象,这自然是不正确的: https//github.com/azmenak/react-stripe-checkout/issues/121#issuecomment-431635855

希望这清除DOM Elements没有明确地等于React Components。 如果您需要以任何方式操纵DOM,请先以反应方式进行操作。 这是一个边缘情况,我宁愿依靠动态表单的表单验证,而不是手动执行非常繁重的自定义验证。

componentDidMount(){
    document.querySelector("#myElem").innerHTML = "Boom!";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM