反应,如何从同一组件访问渲染函数中的DOM元素 [英] React, how to access the DOM element in my render function from the same component

查看:206
本文介绍了反应,如何从同一组件访问渲染函数中的DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering what's the best practice for accessing the DOM elements inside my render function from the same component. Note that I will be rendering this component multiple times on a page.

例如

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



})

推荐答案

此处,无需使用setTimeout.有一些组件的生命周期方法,其中componentDidMount在渲染之后被调用.因此,您可以在该方法中获取对div的引用.

Here, no need to use setTimeout. There are lifecycle methods for component, of which componentDidMount is called after the render. So, you can get the reference to your div in the method.

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

这篇关于反应,如何从同一组件访问渲染函数中的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆