[英]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.