【发布时间】:2021-04-28 01:46:43
【问题描述】:
我是 React 的初学者,所以请耐心等待))
我有一个带有两个不同按钮的父组件,它们触发一个子组件,这是一个 Modal,它必须根据哪个按钮触发了 Modal,在其中显示不同的数据。这两个组件都是功能组件。子 Modal 应该通过来自父级的 props 接收触发按钮的值。该名称是我用来构造对象名称的单个字母,该名称从 Modal 中定义的两个常量获取模态数据。
当我尝试 console.log 通过道具接收到的按钮名称时,我在控制台中收到“未定义”错误。因此,我无法构造 Modal 的内容。
我更喜欢将我的组件定义为函数,而不是扩展一个类。
我的代码有什么地方做错了吗?
父组件(Experience.jsx):
import React, { useState } from "react";
import Container from 'react-bootstrap/Container';
import Col from 'react-bootstrap/Col';
import Button from 'react-bootstrap/Button';
import ExperienceModal from "./ExperienceModal";
function Experience() {
const [modalShow, setModalShow] = React.useState({
value: false,
bname: ""
});
function defineModal(event) {
setModalShow({value: true, bname: event.target.value})
}
return (
<Container fluid>
<Col><Button value="F" onClick={defineModal}>More Information</Button>{''}</Col>
<Col><Button value="E" onClick={defineModal}>More Information</Button>{''}</Col>
<ExperienceModal
show={modalShow.value}
onHide={() => setModalShow({value: false, bname: ""})}
mshow={modalShow}
/>
</Container>
export default Experience;
子组件(ExperienceModal.jsx):
import React from "react";
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
function ExperienceModal(props) {
var x = props.mshow.bname;
console.log(x);
const F = {
inf1: "test test test",
inf2: "text text text",
inf3: "words words words"
}
const E = {
inf1: "sample text sample text",
inf2: "this is just a sample text",
inf3: "another sample text"
}
return (
<Modal
{...props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
Additional Information
</Modal.Title>
</Modal.Header>
<Modal.Body>
<h4>Centered Modal</h4>
<p>{x.inf1}</p>
<p>{x.inf2}</p>
<p>{x.inf3}</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={props.onHide} variant="success">Close</Button>
</Modal.Footer>
</Modal>
);
}
export default ExperienceModal;
【问题讨论】:
标签: javascript reactjs react-props