简体   繁体   中英

React Refs- Differentiate Between Refs in Same Component

I apologize for the somewhat misleading title, but I didn't know how to summarize my problem. Basically I'm using a combination of refs and anime js, an animation library, to add animations. I have a NotificationBar component that renders a list of Notifications, and when a user clicks delete on one an animation plays and it gets deleted. The problem is anime js uses targets like:

handleDeleteNoti = notification => {
    anime({
        targets: this.notiRef,
        opacity: [1,0],
        duration: 500,
    });

    setTimeout(()=>{this.props.clearNotification(notification._id)}, 450)
}

the notiRef in the targets is targeting all notifications (even though their DOM elements are different), so when one is deleted the animation plays on all of them but only one is deleted. Is there a way to differentiate between DOM nodes? I tried adding unique names to each with no results.

List render:

const notifications = this.props.notifications.map((item, index)=>{
        return(
            <Notification 
                item={item} 
                clearNotification={this.props.clearNotification}
                key={index}
            />
        );
    });

Notification component:

<div 
    className={styles.notification}  
    style={{borderLeft: '5px solid '+color}}
    ref={node=>this.notiRef=node}
    name={this.props.item._id}
>
//Notification Content
</div>

You have to use Refs Array:

this.state = {
  notiRef: this.props.notifications.map(() =>
    React.createRef()
  ) /* Other State Vars */,
};

Then add these refs to your component:

const notifications = this.props.notifications.map((item, index) => {
  return (
    <Notification
      item={item}
      clearNotification={this.props.clearNotification}
      key={index}
      ref={notiRef[index]}
    />
  );
});

Finally pass the Refs Array to anime.js

handleDeleteNoti = (notification) => {
  anime({
    targets: this.notiRef,
    opacity: [1, 0],
    duration: 500,
  });

  setTimeout(() => {
    this.props.clearNotification(notification._id);
  }, 450);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM