![](/img/trans.png)
[英]separating container component from presentational component in react native
[英]React - opening modal from presentational component from another component won't work. Why?
我有2個組件,並且想打開一個模式,但是僅當發生另一個事件時(第一個事件是單擊文本,更改該文本,然后才應該顯示模式)。 我是新來的人,由於我有這兩個事件,我對如何將道具傳遞到另一個組件感到困惑。 我究竟做錯了什么? 謝謝!
應用程序組件
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
display: false,
modal: false
}
this.toggle = function() {
this.setState({
display: !this.state.display
});
}.bind(this);
this.showModal = function() {
this.setState({
modal: true
});
}.bind(this);
this.hideModal = function() {
this.setState({
modal: false
});
}.bind(this);
}
componentDidUpdate(prevProps, prevState) {
if (!prevState.display && this.state.display) {
if (!this.state.modal) {
setTimeout(this.showModal, 1000);
}
}
}
render() {
const msg = this.state.display ? <p>hey</p> : <p>bye</p>,
modal = this.state.modal ? (
<AModal onClick={this.toggle} />
) : null;
return (
<div>
<a onClick={this.toggle}><p>{msg}</p></a>
{modal}
</div>
);
}
}
模態分量
import Modal from 'react-modal';
class AModal extends React.Component {
render() {
const customStyles = {
content: {
top: '50%',
left: '40%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
background: '#91c11e',
transform: 'translate(-50%, -50%)'
}
};
return (
<div>
<Modal
isOpen={this.state.modal}
onAfterOpen={this.afterOpenModal}
onRequestClose={this.hideModal}
style={customStyles}
contentLabel="Example Modal">
<h2>hey</h2>
</Modal>
</div>
);
}
}
模態isOpen
由class AModal
的狀態控制,而不是由class App
class AModal
的狀態控制。
<Modal
isOpen={this.state.modal}
...
</Modal>
我相信您將需要將控制模式的隱藏/可見狀態的道具傳遞給該組件。
所以像這樣(用this.state.modal
或this.state.display
替換狀態:
<AModal
onClick={this.toggle}
isOpen={this.state.whatever_state_property_controls_modal_visibility} />
然后在您的模態組件中:
<Modal isOpen={this.props.isOpen} ...
順便說一句,我會將您在App
的構造函數中創建的方法更新為類方法:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
display: false,
modal: false
}
this.toggle = this.toggle.bind(this);
// rest of the methods
}
toggle() {
this.setState({
display: !this.state.display
});
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.