首页 > 解决方案 > 使用 styled-components 防止组件重新渲染

问题描述

我试图弄清楚为什么styled-component button在单击 a 时会重新渲染它,而在未设置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} 
  />
)

在此先感谢您的帮助 !

标签: javascriptreactjsstyled-components

解决方案


您应该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;

推荐阅读