【问题标题】:React-Router not correctly rendering Styled-Components StylesReact-Router 未正确呈现 Styled-Components 样式
【发布时间】:2019-10-16 15:24:14
【问题描述】:

问题是,当我导航到“发布”、展开屏幕,然后使用浏览器返回时,它没有显示正确的 CSS 样式,它使用的是展开视图中的样式,而不是“非扩展'视图。如果我使用 Inspect Element 在组件上切换样式,它会立即解决问题。我知道我可以通过在页面上添加一个后退按钮来规避这个问题,我可能会这样做,但是那些使用浏览器后退按钮的人呢?

我正在尝试对不同的页面使用相同的 StyledComponent。这是我的路由器的代码

<Router>
      <Route
        exact
        path="/"
        render={() => posts.map((post, key) => <Post data={post} key={key} />)}
      />
      <Route
        exact
        path={`/posts/:post`}
        render={currentPath => renderCurrentPost(currentPath)}
      />
    </Router>

第二条路线所做的就是找到要渲染的正确帖子,然后渲染它。

这是我的特定样式组件的代码。

import Styled from 'styled-components';
const Title = Styled.h1`
    @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
    font-family: 'Roboto', sans-serif;
    font-style: medium;
    color: ${props => (props.expanded ? `white` : `#111111`)}
    font-size: ${props => (props.expanded ? `5vh` : `1.2em`)}
    margin: 0 0 0 0;
    align-self: flex-end;
    /* display: inline; */
    position: ${props => (props.expanded ? `relative` : ``)};
    top: ${props => (props.expanded ? `70%` : ``)};    
    left: ${props => (props.expanded ? `5%` : ``)};
     `;

export default Title;

我在这些组件中大量使用道具,因为它会改变它的呈现方式。

这是您第一次导航到着陆页时正确呈现的所需样式。

这是当您使用浏览器后退按钮从展开的帖子页面导航返回时出现的不想要的样式。

【问题讨论】:

    标签: reactjs react-router styled-components


    【解决方案1】:

    我自己回答了这个问题,慢慢地从我的样式组件中删除每一行 CSS 以找到问题,结果是这行代码

    padding: ${props => (props.expanded ? `` : `0 2% 0 10%`)};
    

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 2020-04-04
      • 2018-10-20
      • 2021-01-05
      • 2019-12-21
      • 2019-12-21
      • 1970-01-01
      • 2020-08-31
      • 2021-11-04
      相关资源
      最近更新 更多