[英]How to correctly call function from component in another component
我看到了一些類似的問題,但是關於父/子元素,我有那種節點樹:
IndexPage -> Modals -> ClientDetails(it's modal component)
-> Header
我想在 Header 中調用 ClientDetails.openModal,嘗試了很多方法,比如在 indexPage 中為 ClientDetails 創建引用,然后將 indexPage 傳遞給像 prop 一樣的標題,但它的工作方式很奇怪,我看到了 props.IndexPage 的引用,但是當嘗試直接訪問引用時,它是underfind
class IndexPage extends React.Component {
constructor(props) {
super(props);
this.modals = React.createRef();
}
render() {
return (
<Layout>
<SEO/>
<Header indexPage={this}/>
<Story/>
<Products/>
<Clients/>
<Reviews/>
<Partners/>
<Footer/>
<Modals ref={this.modals} />
</Layout>
)
}
}
class Modals extends React.Component {
constructor(props) {
super(props);
this.clientDetailsRef = React.createRef();
}
render() {
return (
<>
<ThankYou/>
<ContactDetails ref={this.clientDetailsRef}/>
</>
)
}
}
class Header extends React.Component {
constructor(props) {
super(props);
this.state = { isActive: false, isSticky: false };
this.toggle = this.toggle.bind(this);
this.indexPage = props.indexPage
console.log(this.indexPage)
console.log(this.indexPage.modals)
}
}
這是一個從父級調用子函數的小小提琴
https://jsfiddle.net/c1qfn9Lx/9/
class Modal extends React.Component {
constructor(props) {
super(props);
this.state= {
showModal: false
}
this.toggleModal = this.toggleModal.bind(this)
}
toggleModal() {this.setState({showModal: !this.state.showModal})}
render() {
const { showModal } = this.state;
return(
<div className="modal">
{showModal &&
<div>
Showing modal
</div>
}
</div>
)
}
}
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.modalRef = React.createRef()
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.modalRef.current.toggleModal();
}
render() {
return (
<div className="parent">
<Modal ref={this.modalRef} />
<button onClick={this.handleClick}>Click</button>
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
我會嘗試這樣做:
class IndexPage extends React.Component {
constructor(props) {
super(props);
this.state = {modalsRef: null};
}
render() {
return (
<Layout>
<SEO/>
<Header modalsRef={this.state.modalsRef}/>
<Story/>
<Products/>
<Clients/>
<Reviews/>
<Partners/>
<Footer/>
<Modals ref={r => !this.state.modalsRef && this.setState({modalsRef:r})} />
</Layout>
)
}
}
但請注意:該屬性很可能在 Header 的構造函數中不起作用。 它應該在您執行 Button.onClick 回調之類的操作時起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.