gpt4 book ai didi

javascript - react 动画不起作用

转载 作者:行者123 更新时间:2023-12-03 07:19:30 25 4
gpt4 key购买 nike

我有一个 Notification 类来管理从 UI 中创建/删除通知。我可以成功显示/隐藏通知,但通知不会以动画方式显示/显示。

import React from 'react'
import addons from 'react/addons'

const ReactCSSTransitionGroup = React.addons.CSSTransitionGroup

let id = 0
export default class Notification {

constructor (content, className) {

let div = document.createElement('div')
document.body.appendChild(div)

let onClose = () => React.unmountComponentAtNode(div)

React.render(
<NotificationElement className={ className } id={ id++ } onClose={ onClose }>
{ content }
</NotificationElement>,
div
)

}

}

class NotificationElement extends React.Component {

constructor(_) {
super(_)
}

render() {

const className = `Notification ${ this.props.className }`

return (
<ReactCSSTransitionGroup transitionName="slideIn">
<div className={ className } key={ this.props.id }>
{ this.props.children }
<a className="close-button" onClick={ this.props.onClose }>&times;</a>
</div>
</ReactCSSTransitionGroup>
)

}

}

最佳答案

ReactCSSTransitionGroup 只会在其子项添加到其 props 中或从中移除时对其子项进行动画处理。在你的例子中,你的 ReactCSSTransitionGroupchildren Prop 永远不会改变。

以下是您可以改为执行的示例:

let notificationsContainer = document.createElement('div');
document.body.appendChild(notificationsContainer);

let notifications = [];
function renderNotifications() {
React.render(<Notifications notifications={notifications} />, notificationsContainer);
}

class Notifications extends React.Component {

render() {
return (
<ReactCSSTransitionGroup transitionName="slideIn">
{this.props.notifications.map(notification =>
<NotificationElement
key={ notification.id }
className={ notification.className }
onClose={ notification.onClose }
children={ content }
/>
)}
</ReactCSSTransitionGroup>
);
}

}

let id = 0
export default class Notification {

constructor (content, className) {

let notification = {
id: id++, content, className,
};

notification.onClose = () => {
notifications.splice(notifications.indexOf(notification), 1);
renderNotifications();
};

notifications.push(notification);
renderNotifications();

}

}

class NotificationElement extends React.Component {

constructor(_) {
super(_)
}

render() {

const className = `Notification ${ this.props.className }`

return (
<div className={ className }>
{ this.props.children }
<a className="close-button" onClick={ this.props.onClose }>&times;</a>
</div>
)

}

}

每次添加或删除通知时,都会从 ReactCSSTransitionGroupchildren 属性中添加或删除其对应的元素,然后可以正确地对其进行动画处理。

关于javascript - react 动画不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29884848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com