【问题标题】:How to get width of element using React ref?如何使用 React ref 获取元素的宽度?
【发布时间】:2019-08-02 07:59:22
【问题描述】:

我有一个选择字段,但我无法使用 React Ref 获取此选择的宽度。

this.selectRef.current 是一个对象,但似乎没有办法获取元素的宽度

     <Select
        fullWidth
        ref={this.selectRef}
        onChange={event => {
          this.setState({
            value: event.target.value
          });
        }}
        value={this.state.value}
      >
        <MenuItem value={0}>Zero</MenuItem>
        <MenuItem value={1}>One</MenuItem>
        <MenuItem value={2}>Two</MenuItem>
        <MenuItem value={3}>Three</MenuItem>
        <MenuItem value={4}>Four</MenuItem>
      </Select>

沙盒示例https://codesandbox.io/embed/hungry-galileo-eydfw

【问题讨论】:

  • 嗨 fetchenko,请尝试下面的解决方案,如果有帮助,请告诉我:)

标签: javascript reactjs material-ui


【解决方案1】:

只需将Select 组件包装在div 中,然后将div 赋予ref

此外,尝试使用state 记录宽度并在渲染之外定义该引用宽度读取逻辑。把它放在componentDidMount() 中,这样我们就确保了元素已经渲染到屏幕上,我们不需要检查ref.current 是否为真。

您也可以使用.clientWidth 代替.offsetWidth 以获得实际元素宽度,不包括边框。

See working sandbox

import React, { Component } from "react";
import { Select, MenuItem } from "@material-ui/core";

class MySelect extends Component {
  constructor(props) {
    super(props);

    this.state = {
      value: 0,
      open: false,
      width: null
    };

    this.selectRef = React.createRef();
  }

  componentDidMount() {
    const width = this.selectRef.current.clientWidth;
    this.setState(
      {
        width: width
      },
      () => console.log(this.state.width)
    );
  }

  render() {
    return (
      <div ref={this.selectRef}>
        <Select
          fullWidth
          ref={this.selectRef}
          onChange={event => {
            this.setState({
              value: event.target.value
            });
          }}
          value={this.state.value}
        >
          <MenuItem value={0}>Zero</MenuItem>
          <MenuItem value={1}>One</MenuItem>
          <MenuItem value={2}>Two</MenuItem>
          <MenuItem value={3}>Three</MenuItem>
          <MenuItem value={4}>Four</MenuItem>
        </Select>
      </div>
    );
  }
}

export default MySelect;

【讨论】:

    猜你喜欢
    • 2020-06-30
    • 2020-10-12
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    相关资源
    最近更新 更多