如何在Reactjs中获得子级宽度

时间:2019-07-17 07:12:29

标签: javascript reactjs

这是在线示例https://codesandbox.io/s/jovial-resonance-5mjq0

const Parent = styled.div`
  display: flex;
  width: 100%;
  background: yellow;
  justify-content: space-between;
`;

const Children = styled.div`
  display: flex;
  background: tomato;
  height: 50px;
  flex: 0 0 10%;
`;

function App() {
  return (
    <Parent>
      <Children />
      <Children />
      <Children />
      <Children />
      <Children />
    </Parent>
  );
}

因此,无论窗口大小如何调整。 因此,纯javascript可以像

一样完成
document.querySelectorAll(CHILDREN).forEach(e=> {
e.clientWidth
})

但是如何获得<Children />的宽度?我知道在reactjs中播放DOM可能并不常见。但是有一种获取宽度的反应方法吗?谢谢

1 个答案:

答案 0 :(得分:2)

使用refs获取DOM元素(呈现后)。如果需要多个元素的宽度,则可以使用多个引用和一些算术运算,或者使用包围式父级。

class MyComponent extends React.Component {
  constructor() {
    super();
    this.elementRef = React.createRef();
  }
  
  componentDidMount() {
    // get the BCR of your ref
    const bcr = this.elementRef.current.getBoundingClientRect()
    console.log({ width: bcr.width });
  }
  
  render() {
    return (
      <div style={{ width: '234px' }}>
        <div ref={this.elementRef} style={{ width: '50%' }}>
          Hello, World!
        </div>
      </div>
    );
  }
}

ReactDOM.render(<MyComponent />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

相关问题