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