我正在尝试: 使一个选项卡处于事件状态并关闭所有其他选项卡。 目前我只让它在一次关闭和打开一个的地方工作。
我正在尝试弄清楚如何才能做到这一点。 我在想是否有一种方法可以将父组件传递给函数,然后能够访问其所有子组件的 className 属性? 目前我有:
import React from 'react';
import ReactDOM from 'react-dom';
export default class TestContainer extends React.Component{
setActive(event){
event.preventDefault();
//getting id from component
let isActive = event.target.id;
if(event.currentTarget.className === "list-group-item text-center active"){
event.currentTarget.className = "list-group-item text-center";
} else if(event.currentTarget.className === "list-group-item text-center") {
event.currentTarget.className = "list-group-item text-center active";
}
}
render(){
return (
<div className="col-lg-6 col-md-6 col-sm-6 col-xs-6 bhoechie-tab-container scroll-y">
<div className="col-lg-2 col-md-2 col-sm-2 col-xs-2 bhoechie-tab-menu">
<div className="list-group">
<a href="#" onClick={this.setActive} id="eyes" className="list-group-item text-center active">
<h4 className="glyphicon glyphicon-eye-close"></h4><br/>1
</a>
<a href="#" onClick={this.setActive} id="hair" className="list-group-item text-center">
<h4 className="glyphicon glyphicon-tint"></h4><br/>2
</a>
<a href="#" onClick={this.setActive} id="mouth" className="list-group-item text-center">
<h4 className="glyphicon glyphicon-minus"></h4><br/>3
</a>
<a href="#" onClick={this.setActive} id="clothing" className="list-group-item text-center">
<h4 className="glyphicon glyphicon-user"></h4><br/>4
</a>
<a href="#" onClick={this.setActive} id="props" className="list-group-item text-center">
<h4 className="glyphicon glyphicon-gift"></h4><br/>5
</a>
</div>
</div>
)}
最佳答案
通过尝试在 render()
方法之外更改元素的状态,您正在对抗 React 渲染引擎的优势。使用组件内部的状态或通过 props/context(最好是 props)提供的状态来确定哪个选项卡应在其 className 中使用 active
进行渲染。
当您响应点击时,更改状态并让 React 根据新状态重新渲染组件。
对于此处提供的有限示例,我建议将事件元素的 ID 存储在组件状态的内部。
export default class TestContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
activeTab: this.props.activeTab || 'eyes'
};
}
setActive(event) {
this.setState({ activeTab: event.target.id });
}
render() {
const { activeTab } = this.state;
const tabClassName = "list-group-item text-center";
const eyesTabClassName = tabClassName + (activeTab === 'eyes' ? ' active' : '');
...
<a href="#" onClick={this.setActive} id="eyes" className={eyesTabClassName}>
...
}
}
这是一个粗略的、未经优化的解决方案,但它应该能够传达这个想法。当您调用 this.setState 时,React 会通过将组件标记为需要重新渲染来进行响应。 render() 方法将自动被调用,因此所有 JSX 都将被重新评估和重新渲染。然后,React 将查看它刚刚生成的内容与虚拟 DOM 中已有内容之间的差异,并合并您的更改。
这意味着之前在其 className 中使用“active”呈现的任何选项卡都将重新呈现。如果它不再处于事件状态,您的渲染代码将不会将事件类连接到该选项卡的 className 中。此外,无论哪个类处于事件状态,其类名都会附加“active”。
TL;DR
不要在事件处理程序中操作 DOM。操纵状态并让 React 通过使用新状态重新渲染来发挥其魔力。
关于javascript - 将选项卡设置为事件状态时,所有选项卡都会变为 false 算法 Meteor React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37867374/