React中的亲子关系

时间:2019-01-31 09:35:29

标签: reactjs

使用ReactJS解析对子类的引用时遇到一些问题
这是我所有参考文献所在的主要班级:

class App extends Component {
  render() {
    return (
      <div className="App">
        <Navbar />
        <Title content="I am Tristan Vermeesch" />
        <hr />
        <Bio />
        <Introduction ref={(Introduction) => { this.introref = Introduction; }} />
        <Timeline ref={(Timeline) => { this.timelineref = Timeline }} />
        <Projects ref={(Projects) => { this.projectsref = Projects }} />
        <Skills ref={(Skills) => { this.skillsref = Skills }} />
        <Certificates ref={(Certificates) => { this.certifref = Certificates }} />
        <Download ref={(Download) => { this.downloadref = Download }} />
        <Contact ref={(Contact) => { this.contactref = Contact }} />
      </div>
    );
  }
}


我希望我的<Navbar />中的Child组件检索引用以使其使用react-scroll-to-component向下滚动。这是我的Navbar类:

class Navbar extends Component {
    render() {
        return (
            <div className="navbar" >
                <Route path="/textversion" component={TextVersion} />
                <Navitem dName={"Text Version"} url={"textversion"} />
                <Navitem dName={"Contact"} url={"contact"} />
                <Navitem dName={"Resume"} url={"resume"} />
                <Navitem dName={"Certificates"} url={"certificates"} />
                <Navitem dName={"Skills"} url={"skills"} onClick={() => scrollToComponent(this.skillsref, { duration: 1600 })} />
                <Navitem dName={"Projects"} url={"projects"} />
                <Navitem dName={"Life"} url={"life"} />
                <Navitem dName={"Me"} url={"me"} />
            </div>
        )
    }
}


您可以在其中看到onclick函数,该函数在主类中起作用,但是如何从父类中获取所有引用?

1 个答案:

答案 0 :(得分:1)

尝试类似这样的方法: 您必须在应用程序类中定义它

introref =React.createRef()
timelineref = React.createRef()
projectsref = React.createRef()
skillsref = React.createRef()
certifref = React.createRef()
downloadref = React.createRef()
contactref = React.createRef()

并像这样使用:

 <Introduction ref={this.introref} />
    <Timeline ref={this.timelineref} />
    <Projects ref={this.projectsref} />
    <Skills ref={ this.skillsref} />
    <Certificates ref={this.certifref} />
    <Download ref={this.downloadref } />
    <Contact ref={this.contactref} />

是的,您必须在NavBar中创建道具:

<Navbar
  introref={this.introref}
  timelineref={this.timelineref}
  projectsref={this.projectsref}
  skillsref={this.skillsref}
  certifref={this.certifref}
  downloadref={this.downloadref } 
  contactref{this.contactref}
/>

在NavBar内部,您必须像这样使用:

const { introref,timelineref,projectsref,skillsref,certifref,downloadref,contactref } = this.props

您可以给我们打电话的裁判

introref.current
timelineref.current

所以在您的代码中类似:

<Navitem dName={"Skills"} url={"skills"} onClick={() => scrollToComponent(skillsref.current, { duration: 1600 })} />

我希望它能起作用