gpt4 book ai didi

javascript - 从循环中显示和隐藏 React 中的特定组件

转载 作者:行者123 更新时间:2023-11-30 11:21:26 26 4
gpt4 key购买 nike

每个 div 都有一个按钮。当我按下它时,它必须用相同的键显示 div,并隐藏其他的。最好的方法是什么?这是我的代码

class Main extends Component {
constructor(props) {
super(props);
this.state = {
messages: [
{ message: "message1", key: "1" },
{ message: "message2", key: "2" }
]
};
}
handleClick(message) {
//something to show the specific component and hide the others
}
render() {
let messageNodes = this.state.messages.map(message => {
return (
<Button key={message.key} onClick={e => this.handleClick(message)}>
{message.message}
</Button>
)
});
let messageNodes2 = this.state.messages.map(message => {
return <div key={message.key}>
<p>{message.message}</p>
</div>
});
return <div>
<div>{messageNodes}</div>
<div>{messageNodes2}</div>
</div>
}
}

最佳答案

import React from "react";
import { render } from "react-dom";

class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [
{ message: "message1", id: "1" },
{ message: "message2", id: "2" }
],
openedMessage: false
};
}
handleClick(id) {
const currentmessage = this.state.messages.filter(item => item.id === id);
this.setState({ openedMessage: currentmessage });
}
render() {
let messageNodes = this.state.messages.map(message => {
return (
<button key={message.id} onClick={e => this.handleClick(message.id)}>
{message.message}
</button>
);
});
let messageNodes2 = this.state.messages.map(message => {
return (
<div key={message.key}>
<p>{message.message}</p>
</div>
);
});
const { openedMessage } = this.state;
console.log(openedMessage);
return (
<div>
{openedMessage ? (
<div>
{openedMessage.map(item => (
<div>
{" "}
{item.id} {item.message}{" "}
</div>
))}
</div>
) : (
<div> Not Opened</div>
)}
{!openedMessage && messageNodes}
</div>
);
}
}

render(<Main />, document.getElementById("root"));

Edit zl2vxor7jm

这里的主要概念是下面这行代码。

  handleClick(id) {
const currentmessage = this.state.messages.filter(item => item.id === id);
this.setState({ openedMessage: currentmessage });
}`

当我们映射我们的 messageNodes 时,我们传递消息 ID。当一条消息被点击时,该消息的 id 被传递给 handleClick 并且我们过滤所有不包含被点击消息的 id 的消息。然后,如果状态中有 openedMessage,我们将呈现消息,但同时我们将停止呈现消息节点,使用此逻辑 {!openedMessage && messageNodes}

关于javascript - 从循环中显示和隐藏 React 中的特定组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49711981/

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