最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react-redux get width of component's parent div - Stack Overflow

programmeradmin2浏览0评论

This is part of the component :

import MyComp from '../../lib/MyComp'

const Data = ( { data } ) => (
    <div className="data-box" id="data-box">
        <MyComp data={data} />
    </div>
)

How do I get the width of the data-box div inside MyComp container?

This is part of the component :

import MyComp from '../../lib/MyComp'

const Data = ( { data } ) => (
    <div className="data-box" id="data-box">
        <MyComp data={data} />
    </div>
)

How do I get the width of the data-box div inside MyComp container?

Share Improve this question edited Nov 6, 2018 at 11:40 ninjaPixel 6,3824 gold badges38 silver badges49 bronze badges asked Sep 2, 2016 at 6:31 ChristosChristos 1011 gold badge1 silver badge4 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 13

Check this working demo: JSFiddle:

var Parent = React.createClass({
  render: function() {
    return <div id="parent">Hello Parent<Child></Child></div>;
  }
});

var Child = React.createClass({
  componentDidMount: function() {
    alert('Parent width: ' + this.refs.child.parentNode.clientWidth);
  },
  render: function() {
    return <div ref="child">Hello Child</div>;
  }
});

Stating ref="child" will make the element accessable by the component itself, through this.refs.child. It is the vallina node instance. Using this.refs.child.parentNode.clientWidth will return the parent's width. Or, use this.refs.child.parentNode.getBoundingClientRect().

Reference: React refs

You need to use react refs.

on your MyComp class:

class MyComp extends React.Component {

  //All your PropTypes and functions...

  //New function
  newFunction () {
    console.log(this.refs.refName);
    //This will give you the Data component. There you can call methods to calculate width, or whatever you need to do with that component
  }

  //Your render function
  render() {
    return <div ...whatever you have... ref="refName">
  }
}

You can check react documentation

what should work is something like this MyComp could look like this

render() {
  return <div ref="node"></div>
}

with this.refs.node you get the current dom element and with

this.res.node.parentNode

you should get the parentNode

发布评论

评论列表(0)

  1. 暂无评论