【发布时间】:2020-02-25 12:26:18
【问题描述】:
考虑下面的代码,我需要通过 props 将对象格式的 id 传递给另一个组件。但我尝试了很多次,但它不起作用。我想我可能有一些错误,但我不确定它在哪里。
主页(更新):
render(props){
const data = this.state.data;
return (
<div>
<Header />
<NavigationBar />
<PurchaseInfoView show={this.state.displayModal} closeModal={this.closeModal} value={this.openModal}/>
<div className="purchase-side">
<div className="side-title">
<h1>Purchase Order List</h1>
</div>
<hr class="solid" />
{
Object.keys(data).map((key) =>
<div className="list-item">
<h2 onClick= {() => this.openModal(data[key].id)}> //get id
{ data[key].item_name}
</h2>
</div>
)}
</div>
<div className="dads">
</div>
</div>
);
}
openModal(更新):
openModal = (id) => {
this.setState(
{
displayModal: true,
id: id
});
console.log(id) // i can get the id from here id=1
};
PurchaseInfoView 获取 id(更新)。
class PurchaseInfoView extends Component {
render() {
console.log(this.props.id) // get undefined
return (
<div className="Modal"
style={{
transform: this.props.show ,
opacity: this.props.show ? "1" : "0"
}}
>
<h3>Purchase Order detail</h3>
<p>Id: {this.props.id}</p> //cannot get it
</div>
);
}
}
export default PurchaseInfoView;
【问题讨论】:
-
不应该是
this.props.id而不是PurchaseInfoView中的this.props.value.id吗? -
你不会像 props 一样传递 id。Ofc 将是未定义的。
标签: reactjs react-props