gpt4 book ai didi

javascript - ReactJS 通过 props 回调设置另一个类的状态

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

我正在尝试让 fullcalendar 与 ReactJS 和 Bootstrap 模态配合得很好。我想要的是每当用户选择一个日期时,都会出现一个包含所选日期的 Bootstrap 模式。

https://jsfiddle.net/16j1se1q/1/

这是我的代码

class Application extends React.Component {
render() {
return (
<FullCalendar />
);
}
}

class FullCalendar extends React.Component {
constructor(props) {
super(props);
this.state = {view: {showModal: false}};
}

handleHideModal(){
this.setState({view: {showModal: false}})
}

handleShowModal(){
this.setState({view: {showModal: true}})
}

render() {
return (
<div>
<div is id="calendar" class="bootswatch-flatly"></div>
{this.state.view.showModal ? <AppointmentPopup handleHideModal={this.handleHideModal}/> : null}
</div>
);
}

componentDidMount() {
var _that = this;
$('#calendar').fullCalendar({
/* ... */
dayClick: function(date, jsEvent, view) {
/* ... */
_that.handleShowModal();
}
});
}

componentWillUnmount() {
$('#calendar').fullCalendar('destroy');
}
}

class AppointmentPopup extends React.Component {
htmlTemplate() {
return (
/* ... */
)
}

render() {
return this.htmlTemplate();
}

componentDidMount() {
var _that = this;
$('.appointment-modal').modal({
show: true,
keyboard: false,
backdrop: 'static'
}).on('hide.bs.modal', function(e) {
/* ... */
});
$('.appointment-modal').on('hidden.bs.modal', this.props.handleHideModal);
}
propTypes:{
handleHideModal: React.PropTypes.func.isRequired
}
}


ReactDOM.render(<Application />, document.getElementById('app'));

我的完整源代码位于:http://pastebin.com/MZbVqYFZ

它工作正常,直到我点击一个日期然后关闭模态。问题是因为状态 view.showModal 没有改变。我得到了错误:this.setState 不是函数似乎 this.props.handleHideModal 被成功调用,但不知何故 this 不是 ReactJS 对象

最佳答案

ReactJS 用于为您自动绑定(bind) 组件到方法。但是对于 es6 风格的组件,你应该像这样自己做:

render() {
return (
<div>
<div is id="calendar" class="bootswatch-flatly"></div>
{this.state.view.showModal ? <AppointmentPopup handleHideModal={this.handleHideModal.bind(this)}/> : null}
</div>
);
}

关于javascript - ReactJS 通过 props 回调设置另一个类的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39587770/

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