javascript - 使用 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}
/>
)
在此先感谢您的帮助 !
解决方案
您应该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;
推荐阅读
- r - Visual Studio Code 中的自动完成功能:R 中的列名
- html - :在尊重父母的填充之前
- swift - Swift 在协议中使用泛型
- ruby-on-rails - Rails Digest::UUID v5 (vs) Postgresql uuid-ossp v5
- node.js - 需要从 ~ 中删除 package.json 并有一个干净的终端负载
- ios - “iPhone 拒绝了发布请求。” 无法调试
- c++ - 可以提升 vf2 处理这种情况的多图吗?
- mysql - MySQL中MyISAM表中一个字段的varchar长度扩展有什么作用?
- python-3.x - 导入 CSV - 将数据从字典写入文件 - 错误
- python - 我无法通过双击执行 .pyw 文件