简体   繁体   English

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

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

I'm wondering what's the best practice for accessing the DOM elements inside my render function from the same component.我想知道从同一组件访问渲染函数中的 DOM 元素的最佳实践是什么。 Note that I will be rendering this component multiple times on a page.请注意,我将在页面上多次渲染此组件。

eg例如

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>
        )



})

You can use ReactDOM.findDOMNode(this) to access the underlying DOM node. 您可以使用ReactDOM.findDOMNode(this)来访问底层DOM节点。 But accessing the DOM node and manipulating like you do is against the React style of programming. 但访问DOM节点并像操作一样操作是违反React编程风格的。 It's better to use a state variable and called the setState method to re-render the DOM. 最好使用状态变量并调用setState方法来重新呈现DOM。

Here, no need to use setTimeout. 在这里,不需要使用setTimeout。 There are lifecycle methods for component, of which componentDidMount is called after the render. 组件有生命周期方法,在渲染后调用componentDidMount So, you can get the reference to your div in the method. 因此,您可以在方法中获得对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>
    );
});

You can make use of ref callback to access the dom element in react, which is what React Docs recommend to follow 您可以使用ref callback来访问react中的dom元素,这是React Docs建议遵循的内容

and do that in the componentDidMount lifecycle function as refs won't be accessible before the DOM is created 并在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 DOCS

here is my solution: To get a computedCss of an specific element, you need to add a ref attribute to the elemenet first. 这是我的解决方案:要获取特定元素的computedCss,您需要首先向elemenet添加ref属性。

enter image description here 在此输入图像描述

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>
}

And then, in the componentDidUpdate() function, get your element's css by using window.getComputedStyle(this.refs.lineChartWrap).XXX enter image description here 然后,在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); } 

You should avoid accessing DOM element because the whole point of react is putting abstraction over dom. 你应该避免访问DOM元素,因为反应的重点是将抽象放在dom上。 React keeps representation of DOM in memory which is referred as VirtualDom. React将DOM表示在内存中,称为VirtualDom。 Working with VirtualDom will make unit testing your application is easier.If you really know what you are doing, here is how to do it: 使用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.

In ComponentDidMount, when your component is mounted its style change will be applied. 在ComponentDidMount中,当您的组件被挂载时,将应用其样式更改。

Just came across this after trying to do form validation before opening a stripe checkout modal with React 14. 刚刚在使用React 14打开条纹结帐模式之前尝试进行表单验证后遇到了这个问题。

I would like to note that you're not actually accessing a DOM Element with references. 我想请注意,您实际上并没有使用引用来访问DOM元素。 You're simply accessing the React Component Object. 您只是访问React组件对象。 Shown here: 如图所示:

在此输入图像描述

The top one is calling ref.ticketForm , the bottom is showing document.getElementById('ticketform') . 最上面一个是调用ref.ticketForm ,底部是显示document.getElementById('ticketform')

The reason I needed to do this was the following: 我需要这样做的原因如下:

<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() is a DOM Element method: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reportValidity reportValidity()是一个DOM元素方法: https//developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reportValidity

Referencing this issue, this person showed this method being used on a reference object, which naturally isn't correct: https://github.com/azmenak/react-stripe-checkout/issues/121#issuecomment-431635855 引用此问题,此人显示此方法用于引用对象,这自然是不正确的: https//github.com/azmenak/react-stripe-checkout/issues/121#issuecomment-431635855

Hopefully this clears up that DOM Elements do not explicitly equal React Components. 希望这清除DOM Elements没有明确地等于React Components。 If you need to manipulate the DOM in any way, do it in a react way first. 如果您需要以任何方式操纵DOM,请先以反应方式进行操作。 This is an edge case where I would rather rely on form validation for a dynamic form than manually doing very heavy custom validation. 这是一个边缘情况,我宁愿依靠动态表单的表单验证,而不是手动执行非常繁重的自定义验证。

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

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

相关问题 在 React 组件的渲染函数中返回 DOM 元素 - Return DOM element in render function of React component 将 DOM 元素渲染到 React 组件中 - Render DOM element into React Component 如何将“ React Component”呈现给DOM - How to render `React Component` not to the DOM 如何在 React 中将 dom 元素从子组件移动到父组件? - How to move a dom element from a child component to a parent component in React? React渲染相同的元素,它是动态组件 - React render same element which is dynamic component 如何在React中的render方法之外的函数中渲染组件? - How to render component from a function outside the render method in React? 如何将 function 从 FUNCTIONAL 传递给 CLASS 组件并在渲染外部访问它(没有 prop ),在反应 js 中使用上下文? - How to pass function from FUNCTIONAL to CLASS component and access it outside of render( without prop ), using context in react js? 如何重新渲染已在 React 组件中删除的子 DOM 元素? - How to re-render a child DOM element that has been deleted within a React component? 使用多个路径渲染相同的组件 React Router Dom - Render Same Component With Multiple Paths React Router Dom React-Router-DOM:无法在同一页面(组件)中呈现链接 - React-Router-DOM: unable to render Link in the same page (component)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM