javascript - 使用 styled-components 防止组件重新渲染

标签 javascript reactjs styled-components

我想弄清楚为什么当我点击 styled-component 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} 
  />
)

在此先感谢您的帮助!

最佳答案

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

关于javascript - 使用 styled-components 防止组件重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57855233/

相关文章:

css - 使用样式组件扩展样式不起作用

javascript - 如何在我的仪表板应用程序中使用其他人的 react 组件?

javascript - SystemJS 和 JS 请求失败的 Plunker

asp.net - 如何使用 javascript 启用 linkbutton 服务器控件?

javascript - 如何使用 Reactjs 显示 xml 数据

reactjs - 缺少必需的错误组件,刷新... Next.JS

javascript - 从对象中删除元素时,它会从 React js 中的父元素中删除

javascript - 在 React-Boilerplate 中使用 Firebase 身份验证时,服务工作线程捕获对 Google 的 __/auth 请求

javascript - 如何修复嵌套样式组件中的缩进 eslint 错误?

javascript - JSON 上的正则表达式替换正在从数组中删除一个对象