【问题标题】:Component is briefly rendering without styles on first render组件在第一次渲染时短暂渲染而没有样式
【发布时间】:2017-01-14 01:51:05
【问题描述】:

当我打开我的 react 应用程序时,下面的组件会闪烁 width:100%,可能是因为它继承自 material-ui 卡。

在我的 react 应用程序中,有很多这样的组件被渲染,每个组件都有自己的宽度,这些宽度基于父组件的数据。我根据道具使用内联样式设置宽度。

据我了解,组件在创建时具有内联样式,应用它应该没有延迟。但是,在应用给定的内联样式之前,我看到所有具有 100% 宽度的 SceneThumb 组件在几分之一秒内。

如果我将 scene-thumb-parent 的 css 更改为包含一些宽度,例如 10%,那么在应用内联样式之前,我会在几分之一秒内看到它们全部为 10%。这让我觉得应用内联 css 有延迟,但这真的让我很困惑..

这是预期的反应吗?还是一般的html?有什么办法可以减少这种内联样式的应用程序延迟?也许这与我从create-react-app 获得的开发热重载设置有关?

SceneThumb.js (与问题无关的代码已省略):

import React, { Component } from 'react';
import './scene-thumb.css';
import Card from 'material-ui/Card';

class SceneThumb extends Component {
  render() {
    return (
      <div
        className='scene-thumb-parent'
        style={{width:this.props.width, left:this.props.left}}
      >
        <Card
          className={this.props.selected?'scene-thumb-selected':'scene-thumb'}
        >
          <span>
              Hello world!
          </span>
        </Card>
      </div>
    );
  }
}

export default SceneThumb;

scene-thumb.css:

.scene-thumb-parent {
  position:relative;
  text-overflow:clip;
  white-space:nowrap;
  overflow:hidden;
  min-width: 12px;
}

.scene-thumb-selected {
  border: 2px solid red;
  border-radius: 5px;
}
.scene-thumb,.scene-thumb-selected {
  padding: 2px;
  margin:2px;
  position:relative;
}

【问题讨论】:

  • 我在这里猜测 width 属性最初是 null 或其他值。请在您的render() 顶部添加console.log(this.props.width) 并发布输出。
  • 请显示你的父组件,可能@Chris 是正确的
  • @Chris 你明白了。根据视频的持续时间计算宽度是一个问题。如果没有加载视频,我使用零作为持续时间,这导致在计算宽度时除以零。你能写一个答案让我接受吗?或者这可能不够笼统,我应该删除这个问题?

标签: css reactjs


【解决方案1】:

width 属性最初为 null 或其他值。片刻之后,道具被更新,触发另一个渲染。这就是为什么您会看到您所说的闪光灯。

您可以通过将以下内容添加到您的 render() 函数来对此进行测试:

console.log(this.props.width)

您可能会看到它至少记录两次不同的值。

有很多方法可以解决这个问题。什么最有意义取决于应用程序的其余部分以及您的个人偏好。无论如何,这是一种方式:

render() {
  if(!this.props.width) return null; //if it's null, render nothing.
  return (
    <div className='scene-thumb-parent' style={{width:this.props.width, left:this.props.left}}>
      <Card className={this.props.selected?'scene-thumb-selected':'scene-thumb'}>
        <span>Hello world!</span>
      </Card>
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多