【发布时间】:2021-04-06 16:31:08
【问题描述】:
我有两个组件,一个父组件和它的子组件。
在父组件中,我为“活动”存储了一个状态,该状态包含活动子组件的 ID。我想做的是有一个handleClick函数,它将被点击的子组件的id与'active'的值进行比较,如果它相同或不同,我希望它更新html className子组件实现一定的样式效果(可能包括一些动画)。
问题: 有没有办法以特定子元素的 className 为目标并对其进行更新?
在父组件的状态中存储“活动”子组件的 id 时,在子组件本身中处理此函数是否更好?
如果我希望基于子组件的类名从一个类名更改为另一个类名来实现 css 动画,是否还有其他考虑因素,例如包括动画在组件的渲染上运行,如果我是希望以这种方式动画变化?
我确信还有其他方法可以解决这个问题,我完全愿意接受有关实现上述目标的最佳方法的建议,但我还要包括我刚刚开始使用 react 并且还没有学习关于如何使用钩子呢。我仍在使用基本的功能和基于类的组件。
提前致谢,示例代码和下面的伪代码。
示例父组件:
import React, {Component} from "react";
import Task from './openTasks';
import TasksData from './tasks-data';
class openTaskAccordion extends Component{
constructor(){
super()
this.state = {
//holds the id of the currently opened/active item but initialized to -1 since there is no item with an id of -1 at initialization.
active: -1
}
this.handleClick() = this.handleClick.bind(this);
}
handleClick(){
//if (the id of the clicked task === this.state.active){
// change the className of the clicked child component to "closed"
// } else {
// change the className of the child component with id == this.state.active to "closed", change the className of the clicked child component to "open" and update this.state.active to the id of the now open child component with setState.
//
}
render(){
const Tasks = TasksData.map(task=> <Task key={task.id} task ={task}/>)
return(
Tasks
)
}
}
export default openTaskAccordion
示例子组件
import React from "react";
import "./OpenTasks.css"
function openTasks(){
return (
<div id = {props.task.id} className="tasks" value = {props.task.id}>
<h1 >{props.task.clientName}</h1>
<div className="accordion-item accordion-item-closed" >
<h2>{props.task.matter}</h2>
<p> - {props.task.matterStatus}</p>
</div>
</div>
);
}
export default openTasks
【问题讨论】:
标签: javascript reactjs