Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 防止使用样式化组件重新渲染组件_Javascript_Reactjs_Styled Components - Fatal编程技术网

Javascript 防止使用样式化组件重新渲染组件

Javascript 防止使用样式化组件重新渲染组件,javascript,reactjs,styled-components,Javascript,Reactjs,Styled Components,我试图弄清楚为什么单击样式化组件时会重新呈现按钮,而当按钮未设置样式时不会重新呈现 我有一个功能组件,它可以呈现一个可点击的按钮,并使用样式化组件进行样式化。单击按钮时,会按预期触发操作,但每次单击时都会重新呈现样式化的按钮,我可以从chrome开发工具中看到,每次都会生成一个新的类 import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; con

我试图弄清楚为什么单击
样式化组件时会重新呈现
按钮
,而当
按钮
未设置样式时不会重新呈现

我有一个功能组件,它可以呈现一个可点击的
按钮
,并使用
样式化组件
进行样式化。单击
按钮
时,会按预期触发操作,但每次单击时都会重新呈现样式化的
按钮
,我可以从chrome开发工具中看到,每次都会生成一个新的

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;
从“React”导入React;
从“道具类型”导入道具类型;
从“样式化组件”导入样式化;
常量按钮=({onClickButton})=>{
const WrappedButton=styled.button`
背景色:#CCC;
宽度:2em;
高度:2em;
`;
返回(
)
};
导出默认按钮;
如果按钮未设置样式,则会触发操作,并且不会按预期重新呈现按钮:

return (
  <button 
    type="button"
    onClick={onClickButton} 
  />
)
返回(
)

提前感谢您的帮助

尝试将WrappedButton组件初始化提升到渲染函数之外,如下所示,并使用React.memo将组件记忆/制作为一个
PureComponent

import React,{memo}来自“React”;
从“道具类型”导入道具类型;
从“样式化组件”导入样式化;
const WrappedButton=memo(styled.button`
背景色:#CCC;
宽度:2em;
高度:2em;
`);
const Button=memo({onClickButton})=>{
返回(
)
});
导出默认按钮;

您应该将
包装按钮
移到
按钮
之外。每次使用
按钮
渲染时都会重新创建。这可能是每次重新渲染中新类的原因

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;
从“React”导入React;
从“道具类型”导入道具类型;
从“样式化组件”导入样式化;
const WrappedButton=styled.button`
背景色:#ccc;
宽度:2em;
高度:2em;
`;
常量按钮=({onClickButton})=>{
返回;
};
导出默认按钮;

onClickButton做什么?你在那里设置了状态吗?我不认为这是原因,但你应该将
WrappedButton
移到
按钮之外。每次
按钮
rendersIt是一个连接到父组件中redux存储的函数时,都会重新创建它。谢谢@skovy。我把样式移到了功能组件之外,它现在可以工作了!你应该把你的评论作为一个答案。这非常有帮助!我在我的
样式化组件上有一个转换,它没有启动,因为样式化组件每次都在重新渲染。将其从部件中拔出有帮助。