如何从父组件调用子组件中的函数

时间:2019-05-13 14:21:54

标签: javascript reactjs

当我单击Blog.js中呈现的按钮时,我想在Blogpostreader.js中调用函数showExtraBlogposts()

我试图用onClick = {Blogpostreader.showExtraBlogposts()}来调用它,这表明showExtraBlogposts()不是Blogpostreader的功能...

import React from 'react';
import axios from 'axios';
import Blogpost from './Blogpost.js';

class BlogpostReader extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      blogposts: [],
      blogpostAmount: "",
      counter: 1,
      renderedBlogposts: []
    };
  }

  componentDidMount() {
    //API call
  }

  renderBlogpost(i) {
    // Single blogpost rendered
  }

  showExtraBlogposts() {
    for(this.state.counter; this.state.counter < (this.state.blogpostAmount + 2); this.state.counter++) {
      this.state.renderedBlogposts.push(
        <div key={this.state.blogposts[this.state.counter].id} className="col-12 col-sm-12 col-md-12 col-lg-6 col-xl-6 whole-blogpost">
          {this.renderBlogpost(this.state.blogposts[this.state.counter])}
        </div>)
    }
    this.forceUpdate();
  }

  render() {
    this.state.blogpostAmount = this.state.blogposts.length;
    for (this.state.counter; this.state.counter < this.state.blogpostAmount && this.state.counter < 5; this.state.counter++) {
      this.state.renderedBlogposts.push(
        <div key={this.state.blogposts[this.state.counter].id} className="col-12 col-sm-12 col-md-12 col-lg-6 col-xl-6 whole-blogpost">
          {this.renderBlogpost(this.state.blogposts[this.state.counter])}
        </div>)
    }
    return this.state.renderedBlogposts;
  }
}

export default BlogpostReader;

我的Blog组件如下所示:

import React from 'react';
import BlogpostReader from './BlogpostReader.js';
import BlogpostWriter from './BlogpostWriter.js';

class Blog extends React.Component {  
  render() {
    return (
      <div className="row">
        <div className="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6">
          <div className="wrap">
            <BlogpostWriter className="blogpost-writer"/>
          </div>
        </div>
        <div className="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6">
          <div className="wrap">
            <div className="row">
              <BlogpostReader />
            </div>
            <div className="centered-button">
              <button className="styled-button">Meer laden</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}


export default Blog;

如何解决此问题?

编辑 我已经修改了组件,以便BlogpostReader呈现按钮。比我应该能够调用showExtraBlogposts()方法,但是它一直给我一个错误,因为即使没有单击按钮,我的应用程序也可以运行该方法...我该如何解决此问题?

3 个答案:

答案 0 :(得分:1)

您不能真正从父组件调用子方法。做到这一点的“反应方式”是在父组件中存储一个处于状态的布尔值,以跟踪是否应该显示该布尔值,然后将该布尔值通过孩子的道具传递给孩子。

答案 1 :(得分:0)

使用Callbacks传递数据,在parentjs中不是使用父级的子功能,

How to pass data from child component to its parent in ReactJS?

答案 2 :(得分:0)

React基于一种数据绑定的思想,这意味着父级会跟踪状态并传递状态并通过props起作用。这意味着父组件无法从子组件调用函数,为此,您需要使用Redux等其他库。