【问题标题】:Prevent component re-render with styled-components使用 styled-components 防止组件重新渲染
【发布时间】:2019-09-09 22:08:21
【问题描述】:

我试图弄清楚为什么当我单击 styled-component button 时会重新渲染它,而当 button 没有设置样式时却没有重新渲染。

我有一个函数组件,它呈现一个可点击的button,样式为styled-components。单击button 时,会按预期触发操作,但每次单击都会重新呈现样式化的button,我可以从chrome devtools 中看到每次都会生成一个新的class。

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const Button = ({ onClickButton }) => {
  const WrappedButton = styled.button`
    background-color: #CCC;
    width: 2rem;
    height: 2rem;
  `;

    return (
      <WrappedButton 
        type="button"
        onClick={onClickButton} 
      />
    )
};

export default Button;

当按钮未设置样式时,会触发操作并且按钮不会按预期重新渲染:

return (
  <button 
    type="button"
    onClick={onClickButton} 
  />
)

提前感谢您的帮助!

【问题讨论】:

  • onClickButton 有什么作用?你在那里设置状态,猜猜?
  • 我不认为这是原因,但您应该将WrappedButton 移到Button 之外。 每次Button 呈现时都会重新创建
  • 这是一个连接到父组件中的redux store的函数。
  • 谢谢@skovy。我将样式移到了函数组件之外,它现在可以工作了!你应该让你的评论成为答案。

标签: javascript reactjs styled-components


【解决方案1】:

您应该将WrappedButton 移到Button 之外。每次 Button 渲染时都会重新创建。这可能是每次重新渲染中新类的原因。

import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";

const WrappedButton = styled.button`
  background-color: #ccc;
  width: 2rem;
  height: 2rem;
`;

const Button = ({ onClickButton }) => {
  return <WrappedButton type="button" onClick={onClickButton} />;
};

export default Button;

【讨论】:

  • 这非常有帮助!我在我的styled-component 上有一个没有触发的过渡,因为样式组件每次都重新渲染。将其从组件中拉出会有所帮助。
【解决方案2】:

尝试如下在渲染函数之外提升 WrappedButton 组件初始化,并使用 React.memo 来记忆/使组件成为 PureComponent

import React, { memo } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const WrappedButton = memo(styled.button`
    background-color: #CCC;
    width: 2rem;
    height: 2rem;
  `);

const Button = memo(({ onClickButton }) => {

    return (
      <WrappedButton 
        type="button"
        onClick={onClickButton} 
      />
    )
});

export default Button;

【讨论】:

    猜你喜欢
    • 2020-08-21
    • 1970-01-01
    • 2021-01-07
    • 2021-12-05
    • 2021-09-19
    • 2019-04-19
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    相关资源
    最近更新 更多