[英]How do I create a popup window in react.js when the button and function are in separate file?
問題描述:網頁上有一個按鈕,當我單擊該按鈕時,將出現一個包含圖像的彈出窗口。 該按鈕位於名為“ index.jsx”的文件中,單擊該按鈕將在文件“ popUp.js”中觸發一個函數,該函數將彈出一個窗口。 因此,實質上,按鈕和PopUp函數位於單獨的文件中。
我想將函數編寫為:
export function PopUp (image: Image){
return{
...
};
}
它將具有與https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal相同的效果,只是彈出窗口的內容是圖像而不是文本。 我猜想解決方案的重點是將此網頁上的CSS轉換為react.js,但不確定語法應如何。
關於如何實現這一點的任何想法?
您可以使用react-modal輕松實現。 這是一個示例,作為獎勵,我在單擊打開的圖像時添加了關閉模式。 圖像src及其描述應作為道具在數據對象中傳遞給popUp組件。
PopUp.js:
import React from 'react';
import Modal from 'react-modal';
import ModalButton from './modal-button';
import style from './style.css';
class PopUp extends React.Component {
constructor() {
super();
this.state = { modalOpened: false };
this.toggleModal = this.toggleModal.bind(this);
}
toggleModal() {
this.setState(prevState => ({ modalOpened: !prevState.modalOpened }));
}
render() {
const { data } = this.props;
return (
<div className={style.modalWrapper}>
<ModalButton handleClick={this.toggleModal}>
click to open modal
</ModalButton>
<Modal
className={{ base: [style.base]}}
overlayClassName={{ base: [style.overlayBase] }}
isOpen={this.state.modalOpened}
onRequestClose={this.toggleModal}
contentLabel="Modal with image"
>
<img
onClick={this.toggleModal}
src={data.src}
alt='image displayed in modal'
/>
<span className={style.text}>{data.description}</span>
</Modal>
</div>
);
}
}
export default PopUp;
和分隔的按鈕,根據您的要求:
import React from 'react';
import style from './style.css';
const ModalButton = props => (
<button className={style.button} onClick={props.handleClick}>
{props.children}
</button>);
export default ModalButton;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.