【发布时间】:2019-02-12 20:29:59
【问题描述】:
我在使用 React 构建的一个小型应用程序中遇到了一些问题,我正在创建一个由根节点、子节点和孙节点组成的节点树。当我触发模态的显示功能时,我似乎无法让 React Bootstrap 模态访问子节点的正确 id 属性。
在我的页面组件中,我将一组子节点映射到根节点。作为子节点渲染的一部分,我从父节点传递数据,然后填充一个模式,您可以从中编辑该子节点的名称。子节点的代码如下:
import React, { Component } from 'react';
import "./Nodes.css"
import GrandchildNode from "./GrandchildNode"
import EditNameForm from '../Form/EditNameForm/index';
import { MyModal } from '../Modals';
class ChildNode extends Component {
constructor(props) {
super(props)
this.state = {
modalId: this.props.id
}
}
componentDidMount = () => {
console.log(this.state.modalId)
}
render() {
//console.log(this.state)
let grandchildren = true;
if (this.props.grandchildren.length === 0) {
grandchildren = false
}
return (
<div className='childWrapper'>
<div className="childHeader">
<div className="text" key={this.props.id}>{this.props.name}</div>
<button className="edit" onClick={this.props.showNameEdit}>EDIT
NAME</button>
<button className="delete" onClick={() =>
this.props.handleDelete(this.props.id)}>X</button>
</div>
<div className="childBody">
{grandchildren ?
this.props.grandchildren.map(item => {
return <GrandchildNode key={item.id} name={item.name} parent= {item.parent} value={item.value}></GrandchildNode>
}) : <div>No grandchildren to render</div>
}
</div>
<MyModal
show={this.props.showName}
onHide={this.props.handleModalClose}
>
<EditNameForm
errors={this.props.errorFields}
handleInputChange={this.props.handleInputChange}
name={this.props.name}
newName={this.props.newName}
handleModalClose={this.props.handleModalClose}
handleFormSubmit={this.props.handleNameEdit}
id={this.props.id}
/>
</MyModal>
</div>
)
}
}
export default ChildNode;
当打开 Modal 进行编辑时,它似乎为每个孩子渲染一次 Modal,因此列表中的最后一个孩子最终成为被编辑的孩子 - 例如:Child1 的 id 是“abcd”,Child2 的 id是“efgh”;当我打开模态以编辑 Child1 时,我实际上是在编辑 Child2,因为 Child2 的 id 已被传递到模态中。我可以通过添加到我的 EditNameForm 组件中的一些代码来确认这一点:
class EditNameForm extends Component {
state={
id:this.props.id
}
componentDidMount(){
console.log(this.state.id)
}
console.log(this.state.id) 输出如下内容:
5c6311aa2b0593287832b0a2 EditNameForm.js:10
5c63177d7124e5333886d91d EditNameForm.js:10
我试图了解这里发生了什么,我有一些理论,但它们是预感 - 任何有更多 React 经验的人,你能帮我理解 a)这里发生了什么和 b)我如何设置它up 以便模态以正确的 id 属性打开?
【问题讨论】:
-
你也应该显示为父组件
标签: javascript reactjs react-bootstrap