【问题标题】:How to get the ReactJS element inside componentDidMount()?如何在 componentDidMount() 中获取 ReactJS 元素?
【发布时间】:2017-05-14 21:42:51
【问题描述】:

我有 4 个特定 React 类的实例。在componentDidMount()之后我想存储每个实例的y位置。

如何处理呈现的元素?我不能使用类名,因为我有 4 个相同类的不同位置的元素。

我的 ReactJS 组件:

const Col = React.createClass({
    componentDidMount: function() {
        //here address the actual rendered col-instance
    },

    render() {
        return (
            <div className='col'>
            </div>
        );
    }
});

【问题讨论】:

  • 只是想更多地理解这个问题。您是否尝试存储每个 React 组件实例的 y 位置以供以后使用?安装后每个元素的 y 位置也会发生变化吗?
  • 我需要存储它,它不会改变。也许我可以使用 this.ref ?
  • 您能否进一步解释一下您要达到的目标?你想在哪里存储什么?您希望如何访问存储的值以及从何处访问?
  • @FabianSchultz 在主容器中会有 4 个 -Elements,我想将每个 的 y-pos 存储在 Col-React-Class 内的数组中。
  • 所以每个Col 元素都存储了所有Col 元素的y 值?

标签: reactjs


【解决方案1】:

使用refs

首先,在每个 JSX cols 元素上连接一个 ref 属性。然后,在componentDidMount 方法中使用这个ref 来访问组件的DOM 节点(实际的HTMLElement)。最后,获取元素的位置/偏移量或您需要的任何其他内容。

const Col = React.createClass({
    componentDidMount: function() {
        // this.refs.col1 is the actual DOM element,
        // so you can access it's position / offset or whatever
        const offsetTop = this.refs.col1.offsetTop;
    },

    render() {
        return (
            <div className="col" ref="col1">
            </div>
        );
    }
});

PS:我不确定您所说的元素y 位置是什么意思。无论如何,一旦你知道如何获取 DOM 元素 (this.refs.col1),你就可以使用你需要的 javascript to retrieve the position

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-05-01
  • 2021-06-16
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 2016-05-11
相关资源
最近更新 更多