react-redux获取组件父div的宽度

Chr*_*tos 9 javascript reactjs

这是组件的一部分:

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

const Data = ( { data } ) => (
    <div className="data-box" id="data-box">
        <MyComp data={data} />
    </div>
)
Run Code Online (Sandbox Code Playgroud)

如何data-boxMyComp容器中获取div 的宽度?

Joy*_*Joy 12

检查这个工作演示: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>;
  }
});
Run Code Online (Sandbox Code Playgroud)

声明ref="child"将使元素可以通过组件本身访问this.refs.child.它是vallina节点实例.使用this.refs.child.parentNode.clientWidth将返回父级的宽度.或者,使用this.refs.child.parentNode.getBoundingClientRect().

参考:React refs

  • 谢谢你的回答.JSFiddle链接已经死了. (3认同)

May*_*day 1

您需要使用反应参考。

在您的 MyComp 课程上:

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">
  }
}
Run Code Online (Sandbox Code Playgroud)

你可以查看react文档