【发布时间】:2019-01-03 11:14:13
【问题描述】:
我知道以前有人问过这个问题,但答案似乎总是暗示与这种情况无关的问题,我只是没有看到。
我有一个父组件,它将属性传递给子组件的状态。根据这个传递的属性的值,孩子最初是否显示它的视图。这是我认为 React 的工作方式:
当父级(或一般的组件)的状态发生变化时,它将被重新渲染。当它被重新渲染时,它的所有孩子都会再次收到他们的道具(即孩子的构造函数也被调用了?)。但这显然不是本示例中的工作方式。
父组件:
class FileListTable extends React.Component
{
constructor(props)
{
super(props);
this.state = {
showModal: false
};
this.showSelectFolderModal = this.showSelectFolderModal.bind(this);
}
showSelectFolderModal()
{
this.setState({ showModal: true });
}
render()
{
console.log("Rendering table with showModal = " + this.state.showModal);
return (
<div>
<table id="files-table" class="table">
<tr>
<td>
...
<span class="float-right">
<FileActionMenu
showSelectFolderModal={ this.showSelectFolderModal } />
</span>
</td>
</tr>
</table>
<SelectFolderModal
show={ this.state.showModal }/>
</div>
);
}
}
FileActionMenu子组件:
class FileActionMenu extends React.Component
{
constructor(props)
{
super(props);
}
render()
{
return (
<div class="dropdown">
<button class="btn dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
...
</button>
<div class="dropdown-menu dropdown-menu-right">
<button class="dropdown-item" type="button" onClick={ () => this.props.showSelectFolderModal() }>...</button>
</div>
</div>
);
}
}
SelectFolderModal子组件:
class SelectFolderModal extends React.Component
{
constructor(props)
{
super(props);
console.log("Received props from table");
console.log(this.props);
this.state = { show: this.props.show };
}
closeModal()
{
this.setState({ show: false });
// do something post close
}
render()
{
console.log("Rendering modal with show status: " + this.state.show);
return (
<div id="select-folder-modal" class="modal { this.state.show ? 'show' }" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" onClick={ this.closeModal }>...</button>
</div>
</div>
</div>
</div>
);
}
}
我的初始控制台输出是这样的:
使用 showModal = false 渲染表
从桌子收到道具
{显示:假}
显示状态的渲染模式:false
好的,这是有道理的。但是当我点击FileActionMenu 中的按钮时,我得到以下输出:
使用 showModal = true 渲染表
显示状态的渲染模式:false
所以当父母更新时,父母的状态不会作为道具传递给孩子!但我认为这就是它的工作原理,有人可以帮我解释一下吗?
【问题讨论】:
标签: javascript reactjs