基本上我希望能够检测 react 组件是否有溢出的子组件。就像在 this question 中一样.我发现使用 ReactDOM 也可以做同样的事情,但是 i cannot/should not use ReactDOM .我在建议的替代方案ref
中没有看到任何等效的内容。
所以我需要知道的是,在这些条件下是否有可能检测到 React 组件内的溢出。并且对于同一点,是否可以检测宽度?
最佳答案
除了@jered 的出色回答之外,我还想提一下限定符,即如果将 ref 直接放在DOM 元素。也就是说,它不会以这种方式处理 Components。
所以如果你像我一样有以下情况:
var MyComponent = React.createClass({
render: function(){
return <SomeComponent id="my-component" ref={(el) => {this.element = el}}/>
}
})
并且当您尝试访问 this.element
的 DOM 属性时(可能在 componentDidMount
或 componentDidUpdate
中)并且您没有看到所述属性, 以下可能是适合您的替代方案
var MyComponent = React.createClass({
render: function(){
return <div ref={(el) => {this.element = el}}>
<SomeComponent id="my-component"/>
</div>
}
})
现在您可以执行以下操作:
componentDidUpdate() {
const element = this.element;
// Things involving accessing DOM properties on element
// In the case of what this question actually asks:
const hasOverflowingChildren = element.offsetHeight < element.scrollHeight ||
element.offsetWidth < element.scrollWidth;
},
关于javascript - 如何在没有 ReactDOM 的情况下检测 React 组件的溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42012130/