React.js:参考在初始渲染时不可用 [英] React.js: Refs are not available on initial render

查看:35
本文介绍了React.js:参考在初始渲染时不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在组件的根DOM元素的中间放置一个圆圈:

I’m tying to position a circle in the middle of the component’s root DOM element:

var App = React.createClass({
    render: function() {
        return <svg ref="svg">
            <circle r="9" cx={this.centerX()} cy="15"/>
        </svg>;
    },
    centerX: function() {
        var svg = this.refs.svg.getDOMNode();
        return svg.offsetLeft + Math.round(svg.offsetWidth / 2);
    }
});

http://jsfiddle.net/NV/94tCQ/

鸡和蛋的问题发生在这里: this.refs 在第一个渲染器上未定义.解决这个问题的最佳方法是什么?我不想引用外部 DOM 节点(例如 document.body).

Chicken-and-egg problem takes place here: this.refs is undefined on the first render. What’s the best way to solve this it? I would prefer not to reference external DOM nodes (such as document.body).

推荐答案

不是未定义 refs ,而是您正在尝试同时访问DOM.生成它. this.refs.svg.getDOMNode 将不会返回任何内容,因为该组件在 render 中没有真正的DOM表示.

It's not that refs isn't defined, it's that you're trying to access the DOM at the same time you are trying to generate it. this.refs.svg.getDOMNode will not return anything because the component has no real DOM representation in render.

为了保持更多的React-y,我将 cx 移到组件的状态,并在将元素渲染到DOM之后对其进行更新:

To keep this more React-y, I would move cx to the component's state and update it after the element has been rendered to the DOM:

var App = React.createClass({
    componentDidMount: function() {
        var svg = this.refs.svg.getDOMNode();
        this.setState({
            cx: svg.offsetLeft + Math.round(svg.offsetWidth / 2)
        });
    },
    getInitialState: {
        return {
            cx: 0
        };
    },
    render: function() {
        return (
            <svg ref="svg">
                <circle r="9" cx={this.state.cx} cy="15" />
            </svg>
        );
    }
});

这篇关于React.js:参考在初始渲染时不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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