多个子组件获得相同的道具值

  • 本文关键字:组件 javascript reactjs
  • 更新时间 :
  • 英文 :


我有两个自定义的类组件,我从中创建了两个实例,如:

<PersonAddModal details={details} open={open} setOpen={setOpen} addFather={false}/>

因此,addFather属性不同,其余属性相同。

PersonAddModal如下所示。(添加父亲/添加母亲文本显示正确,取决于addFather的值(

import React from 'react'
import { Modal } from 'react-responsive-modal';

class PersonAddModal extends React.Component 
{
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event)
{
//...
}

getParentTypeString()
{
return this.props.addFather ? "father" : "mother";
}
render() {
return(
<div>
<button onClick={() => this.props.setOpen(true)}>{this.props.addFather ? <div>Add father</div>:<div>Add mother</div>}</button>
<Modal open={this.props.open} onClose={() => this.props.setOpen(false)}>
<h1>Add a {this.getParentTypeString()} of {this.props.details.firstName}</h1>
<form onSubmit={(event) => {this.handleSubmit(event)}}>
<input type="text" id="firstName" name="firstName" placeholder="Enter first name" required/>
<input type="text" id="lastName" name="lastName" placeholder="Enter last name" required/>
<button type="submit">Submit</button>
</form>
</Modal>
</div>
)};
}
export default PersonAddModal;

我真的不明白为什么(显然(最新添加的组件的addFather的val似乎也用于第一个组件。难道他们不应该彼此独立吗?非常感谢您的帮助!

编辑:他们重新使用如下:

import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import 'react-responsive-modal/styles.css';
import { Modal } from 'react-responsive-modal';
import PersonLink from './PersonLink'
import PersonAddModal from './PersonAddModal'
const PersonDetails = ({ match }) => {

const [details, setDetails] = React.useState({});
const [isLoading, setIsLoading] = React.useState(true);
const [open, setOpen] = React.useState(false);
React.useEffect(() => {
fetch(`https://localhost:44332/api/person/${match.params.id}/details`)
.then(response => response.json())
.then((data) => { setDetails(data); setIsLoading(false); });

}, [match.params.id])
return (
<>
{
(isLoading || details.id == null) ? <h1>Loading..</h1>
:
<>
<h1>Person Details of {details.firstName} {details.lastName}</h1>
<h2>Parents </h2>
{
details.father != null && details.father != 0 ?
<PersonLink id={details.father  } />
:
<>
<PersonAddModal details={details} open={open} setOpen={setOpen} addFather={true}/>
</>
}
{
details.mother != null && details.mother != 0 ?
<PersonLink id={details.mother} />
:
<PersonAddModal details={details} open={open} setOpen={setOpen} addFather={false}/>
}
{details.spouse != 0 ?
<>
<h2>Spouse</h2>
<PersonLink id={details.spouse}/>
</>
: <></>}
<h2>Siblings</h2>
{
details.siblings.map((sibling) => (<PersonLink id={sibling} />))
}
<h2>Children</h2>
{
details.children.map((child) => (<PersonLink id={child} />))
}
</>
}

</>
);
};

export default PersonDetails;

我找到了答案:

正如你所看到的,我正在创建两个模态,我的问题是两者显示的是相同的。事实证明,因为我给了它们相同的状态(open/setOpen(,所以无论我点击哪个,打开的总是相同的。

最新更新