我将Chat组件两次重用到另一个组件中。单击“聊天”按钮时显示,但彼此重叠。
if(...)break;
我希望一次显示一个聊天。当我单击“聊天”按钮2并显示“聊天1”时,应该隐藏“聊天1”。
答案 0 :(得分:1)
本质上,您需要为每个Chat
组件提供一个标识符,并跟踪当前打开的组件。
这是父项组件的基本结构:
class App extends React.Component {
state = {
currentChatId: null
};
handleOpen = id => {
this.setState({
currentChatId: id
});
};
render() {
return (
<div>
<Chat
identifier={1}
currentChatId={this.state.currentChatId}
handleOpen={this.handleOpen}
/>
<Chat
identifier={2}
currentChatId={this.state.currentChatId}
handleOpen={this.handleOpen}
/>
</div>
);
}
}
因此请注意,我们给每个Chat
组件一个identifier
道具。我们将使用identifier
更新活动聊天-我们将其存储为名为currentChatId
的父状态。这一切都是通过handleOpen()
事件处理程序完成的,我们也将其作为Chat
的支持对象。
现在在您的Chat
组件中,我们需要为open()
和componentDidUpdate()
配置逻辑
class Chat extends React.Component {
constructor() {
super();
this.state = {
show: false
};
}
componentDidUpdate(prevProps) {
const { identifier, currentChatId } = this.props;
if (this.props.currentChatId !== prevProps.currentChatId) {
this.setState({
show: identifier === currentChatId ? true : false
});
}
}
open = () => {
const { identifier, handleOpen } = this.props;
handleOpen(identifier);
};
render() {
return (
<div className="chat">
<button className="btn-yes round" onClick={this.open}>
{this.props.title}
</button>
{this.state.show && (
<div className="show-chat">
<div className="chat-head">
Now Chatting{" "}
<i className="fas fa-angle-down" onClick={this.close} />
</div>
<div className="chat-body">
<div className="blue">
Teresa wants to chat about her healthcare finances
</div>
<ul>
<li>
<img src={""} alt="chat agent avatar" />
</li>
<li>
<h6>John Newman</h6>
<div className="gray">Hi Teresa!</div>
<div className="gray">
Here is the <a href="/">link to the finance tool</a> we
discussed.
</div>
<div className="gray">
If you have any questions, let me know!
</div>
</li>
</ul>
</div>
<input placeholder="Type here and hit enter to chat" />
</div>
)}
</div>
);
}
}
工作流程:
handleOpen()
,我们
传递唯一的identifier
.... Parent
,现在传递到currentChatId
应该用identifier
... currentChatId
作为
currentChatId
道具... componentDidUpdate()
,我们检查
currentChatId
与自己的标识符相对应,则只有一个
匹配,因此我们将其显示出来。有关工作示例,请参见codeandbox:https://codesandbox.io/s/react-example-kgm2h