为何styled-components按钮点击会重复渲染,原生按钮却不会?
嘿,我来帮你搞清楚这个问题!
问题根源
你遇到的核心问题是把styled-components定义的组件放在了函数组件的内部。
每次你的Button组件触发重渲染(比如点击按钮时),函数组件的代码会重新执行一遍,这就意味着每次都会重新创建一个全新的WrappedButton组件。styled-components会为每个新创建的组件生成唯一的类名,这就是你在Chrome DevTools里看到每次点击都有新类名的原因。而这个全新的组件自然会触发重渲染——相当于你每次都在渲染一个完全不同的组件,而非同一个组件的状态更新。
反观原生<button>,它是React内置的基础组件,不会因为你的函数组件重渲染而被重新定义,所以只有当必要的状态变化时才会触发重渲染,不会有额外的无意义重渲染。
解决方案
只需要把styled-components定义的组件移到函数组件的外部,让它只被创建一次即可:
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; // 将WrappedButton移到组件外部,仅初始化一次 const WrappedButton = styled.button` background-color: #CCC; width: 2rem; height: 2rem; `; const Button = ({ onClickButton }) => { return ( <WrappedButton type="button" onClick={onClickButton} /> ) }; export default Button;
如果你的样式需要依赖组件内部的props做动态调整,也不用把组件放回内部,而是通过styled-components的props传递能力实现:
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; // 通过props接收动态样式参数 const WrappedButton = styled.button` background-color: ${props => props.bgColor || '#CCC'}; width: 2rem; height: 2rem; `; const Button = ({ onClickButton, bgColor }) => { return ( <WrappedButton type="button" onClick={onClickButton} bgColor={bgColor} /> ) }; export default Button;
这样调整后,WrappedButton只会被创建一次,类名也会保持稳定,点击按钮时就不会再出现无意义的重渲染了。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

