问题描述
我遇到一个问题,如果我将子组件分离到主要组件之外,关键帧动画将停止工作。
有问题的动画是一个简单的扩展容器,每次容器的内容更改时都会播放。
我的Abouts.js(主要组件):
const About = React.forwardRef((props,ref) => {
const [ topic,setTopic ] = useState('react')
const [ logo,setlogo ] = useState(topicslist[0].logo)
const [ active,setActive ] = useState(0)
...
const handletopicChange = (topic,index,logo) => {
setTopic(topic.toLowerCase())
setlogo(logo)
setActive(index)
}
//Creates buttons from a list of topics and adds the functionality to switch between them
const createButtons = () =>
topicslist.map((topic,index) => (
<Button
key={topic.name.toLowerCase()}
onClick={() => handletopicChange(topic.name,topic.logo)}
active={active === index}
>
{topic.name.toLowerCase().includes('csharp') ? 'C#' : topic.name.toupperCase()}
</Button>
))
...
//Renders the Container with content based on the topic hook which gathers content from an i18next file
const Topic = props => {
const value = props.value.includes('c#') ? 'csharp' : props.value
return (
<TopicContainer>
<TopicTitle
style={{ textAlign: 'left' }}
$color={props.theme === dark ? dark.colors[value] : light.colors[value]}
>
{t(`titles.about.${value}`)}
</TopicTitle>
<div dangerouslySetInnerHTML={{ __html: props.children }} />
</TopicContainer>
)
}
return(
...
{createButtons()}
<Topic theme={props.theme} value={topic}>
{t(`paragraphs.${topic}`)}
</Topic>
...
)
}
我的styles.js(样式化组件文件):
...
const expand = keyframes`
from {
transform: scale(0.5);
}
to {
transform: scale(1);
}
`
const expandAnimation = css`
animation: css`${expand} 300ms ease`;
`
const blogText = css`
font-size: ${props => props.theme.fonts.size.xs};
font-weight: ${props => props.theme.fonts.weight.normal};
color: ${props => props.theme.colors.neutralLight};
@media ${device.greaterThan.laptopLMin} {
font-size: ${props => props.theme.fonts.size.md};
}
`
export const TopicContainer = styled.div`
${expandAnimation};
${blogText};
width: 85%;
margin: 0 auto;
margin-bottom: 2rem;
& div {
width: 100%;
float: left;
}
& p {
width: 100%;
@media ${device.greaterThan.laptopLMin} {
width: 70%;
}
}
`
...
现在,一切正常,并按预期进行。问题是,当我将子级( Topic )组件移出其父级( About )组件之外时,我的动画将停止工作(除了刷新时的第一个渲染)这一页)。即使容器中的内容像以前一样发生变化,并且控制台中也没有收到任何负面消息。
我会指定我正在使用样式化组件,但是出于相同的目的,我尝试创建一个css文件,以防问题与样式化组件有关,但是结果是相同的。一切正常,直到我的孩子搬出...
如果缺少信息,请告知我。
解决方法
要使动画运行,您需要将props.main或props.signature向下传递到样式化的组件
const expandAnimation = css`
animation: ${props => (props.signature || props.main ? 'none' : css`${expand} 300ms ease;`)};
`const expandAnimation = css`
animation: ${props => (props.signature || props.main ? 'none' : css`${expand} 300ms ease;`)};
`
您的TopicContainer应该是
let isSignature=true;
let isMain=true;
<TopicContainer signature={isSignature} main={isMain}>
<TopicTitle
style={{ textAlign: 'left' }}
$color={props.theme === dark ? dark.colors[value] : light.colors[value]}
>
{t(`titles.about.${value}`)}
</TopicTitle>
<div dangerouslySetInnerHTML={{ __html: props.children }} />
</TopicContainer>
由于我没有找到对签名或主体的任何引用,因此我创建了虚拟变量以作为prop传递。