gpt4 book ai didi

javascript - 从另一个组件打开模态点击 react js

转载 作者:行者123 更新时间:2023-11-30 09:30:13 26 4
gpt4 key购买 nike

我正在使用 React 的基本组件模态组件 - https://github.com/reactjs/react-modal

我想要实现的是,我想从另一个导入了模态的父级打开模态。

Parent.js
<button onClick={() => this.refs.setState({modalIsOpen: true})}> - THIS BUTTON ELEMENT IS IN ANOTHER COMPONENT

Modal.js
import React from 'react';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';

const customStyles = {
content : {
top : '50%',
left : '50%',
right : 'auto',
bottom : 'auto',
marginRight : '-50%',
transform : 'translate(-50%, -50%)'
}
};

class App extends React.Component {
constructor() {
super();

this.state = {
modalIsOpen: false
};

this.openModal = this.openModal.bind(this);
this.afterOpenModal = this.afterOpenModal.bind(this);
this.closeModal = this.closeModal.bind(this);
}

openModal() {
this.setState({modalIsOpen: true});
}

afterOpenModal() {
// references are now sync'd and can be accessed.
this.subtitle.style.color = '#f00';
}

closeModal() {
this.setState({modalIsOpen: false});
}

render() {
return (
<div>
<button onClick={this.openModal}>Open Modal</button>
<Modal
isOpen={this.state.modalIsOpen}
onAfterOpen={this.afterOpenModal}
onRequestClose={this.closeModal}
style={customStyles}
contentLabel="Example Modal"
>

<h2 ref={subtitle => this.subtitle = subtitle}>Hello</h2>
<button onClick={this.closeModal}>close</button>
<div>I am a modal</div>
<form>
<input />
<button>tab navigation</button>
<button>stays</button>
<button>inside</button>
<button>the modal</button>
</form>
</Modal>
</div>
);
}
}

export default App

我读到这可以使用 refs 和改变模态的状态来完成。我到底做错了什么?

谢谢!

最佳答案

你能在父类中试试下面的代码吗

<button onClick={() => this._modal.openModal()}>click</button>

当你调用模态组件时使用 ref然后属性可以像上面的代码一样调用。

<Modal ref={(modal) => { this._modal = modal; }} />

关于javascript - 从另一个组件打开模态点击 react js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46749946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com