【问题标题】:React DOM offsetHeight before rendering在渲染之前反应 DOM offsetHeight
【发布时间】:2016-09-12 22:10:08
【问题描述】:

我需要能够通过它的 offsetHeight 来定位 React DOM 元素。

问题是我无法收集尚未创建的元素的 offsetHeight(因此无法将高度作为参数传递给渲染函数),我也无法计算渲染内部的高度功能如 React DOM refs 文档中所述:

永远不要在任何组件的 render 方法中访问 refs - 或者当任何组件的 render 方法甚至在调用堆栈中的任何位置运行时。

DOM 元素应相对于单击以显示它的图标呈现。

组件树:

|— FormInputGroup
  |— Label
    |— TooltipIcon
  |— Tooltip
  |— Input

工具提示图标的渲染函数:

const TooltipIcon = ({ attribute, setCurrentTooltip }) => (
  <Icon
    name="tooltip"
    style={{
      position: "relative",
      top: "1px",
      marginLeft: "10px",
      "cursor": "pointer",
    }}
    onClick={() => setCurrentTooltip(attribute)}
  />
)

渲染函数:

const Tooltip = ({ title, content, setCurrentTooltip }) => (
  <div className="popover"
    style={{
//      top: "-"+ ReactDOM.findDOMNode(this).offsetHeight +"px",
    }}
  >
    <h3 className="popover-title">{title}</h3>
    <div className="popover-close-button"
      onClick={() => setCurrentTooltip(null)}
    />
    <div className="popover-content">{content}</div>
  </div>
)

这是没有定位的 DOM 元素: not positioned

这是我想要的位置渲染方式(顶部:-(offsetHeight)px: positioned

【问题讨论】:

    标签: javascript css reactjs


    【解决方案1】:

    不确定这是否是最佳解决方案,但您可以使用的一种技术是通过组件状态跟踪您的样式,首先将其初始化为空:

    this.state = { style: {} };
    

    然后在您可以成功访问您要查找的元素后,在 componentDidMount() 函数中更新该状态:

    componentDidMount() {
      this.setState(
        {style: { top: "-" + (ReactDOM.findDOMNode(this).offsetHeight) + "px" } }
      );
    } 
    

    如果需要,将它作为道具传递给任何需要它的子组件。

    我将一个 codepen 和一些 cmets 放在一起以进一步说明:http://codepen.io/anon/pen/vGwyVj

    【讨论】:

      【解决方案2】:

      我自己也遇到过类似的问题,一种解决方法是使用生命周期方法componentDidMount,因此您需要使用受控或“智能”组件。

      DEMO

      class Tooltip extends React.component {
        constructor(props) {
          super(props);
          this.state = {
            mounted: false,
            ... other state stuff
          };
        }
        ....
      }
      

      componentDidMount 中,您将mounted 的状态设置为true,在这里您还可以访问您的组件:

      componentDidMount() {
        this.setState({mounted: true})
        // get your style here...
      }
      

      然后在您的渲染函数中,您根据该状态有条件地渲染组件:

      render() {
         if (this.state.mounted) {
           // return your component with the offset style
           // which you can pass in as a prop...
         } else {
           // you can return a version of the component that is not offset here, 
           // I chose not to do this, React is pretty fast. 
           }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-16
        • 2018-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-21
        相关资源
        最近更新 更多