gpt4 book ai didi

javascript - React,在动态加载的 div 元素上添加 onClick 事件。

转载 作者:行者123 更新时间:2023-12-03 03:08:57 25 4
gpt4 key购买 nike

目前在我的 React 应用程序上,我正在加载许多 div,这些 div 正在动态加载数据库中的信息。我试图做到这一点,以便当我单击这些 div 之一时会出现一个弹出窗口,其中包含与该 div 相关的更深入的数据。然而,它似乎并没有按预期工作。 onClick 不适用于此动态加载的 div。我尝试在我的主应用程序组件上的标准按钮元素上测试弹出窗口,并且它有效。这是我的代码:

class ResultBox extends Component {
constructor(props){
super(props);
this.state = {
showPopup: false,
posts: []
};
}
togglePopup() {
this.setState({
showPopup: !this.state.showPopup
});
}
componentDidMount() {
axios.get('http://localhost:3001/api/events')
.then(res => {
let posts = res.data.map(obj => obj);
this.setState({posts});
console.log(posts);
});
}
render() { ********** Below here is where my issue is *****
return (
this.state.posts.map(events =>
<div key={events.key}
className='result_box'
onClick={this.togglePopup.bind(this)}>

<p>{events.name}</p>
{events.place && events.place.location && <p>
{events.place.location.city}</p>}
</div>
)
{this.state.showPopup ?
<Result
text='Close Me'
closePopup={this.togglePopup.bind(this)}
/>
: null
}
);
}
}

这个 ResultBox 正在 App 中渲染

 class App extends Component {

render() {
return (
<div className="App">
<NavBar className="navbar-body"/>
<div className="spacer"></div>
<p className="App-intro">
Find a jam
</p>
<ResultBox />

</div>
);
}
}

结果只是弹出框组件。如果有人知道我如何让它发挥作用,我将不胜感激。

最佳答案

是的,您需要将帖子数据放在 div 中,这就是我的结构。

class ResultBox extends Component {

constructor(props){

super(props);

this.state = {
showPopup: false,
posts: []
};

this.togglePopup = this.togglePopup.bind(this);
}

togglePopup() {
this.setState({
showPopup: !this.state.showPopup
});
}


componentDidMount() {

axios.get('http://localhost:3001/api/events')
.then(res => {
let posts = res.data.map(obj => obj);
this.setState({posts});
console.log(posts);
});
}

buildRows() {
return this.state.posts.map( (events, index) =>
<div key={index} className='result_box' onClick={this.togglePopup}>
<p>{events.name}</p>
{events.place && events.place.location &&
<p>{events.place.location.city}</p>
}
</div>
);
}

render() {

let rows = this.buildRows();

return (
<div>
{rows}

{this.state.showPopup &&
<Result text='Close Me'closePopup={this.togglePopup.bind(this)}/>
}
</div>
);
}
}

export default ResultBox;

关于javascript - React,在动态加载的 div 元素上添加 onClick 事件。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47025486/

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