gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:40:18 25 4
gpt4 key购买 nike

我想在单击 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;

我的博客组件如下所示:

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() 方法,但它一直给我一个错误,因为我的应用程序即使不单击按钮也会运行该方法...我该如何解决此问题?

最佳答案

您无法真正从父组件调用子方法。执行此操作的“ react 方式”是在父组件中存储一个 bool 值,以跟踪是否应该显示它,然后通过子组件的 props 将该 bool 值传递给子组件。

关于javascript - 如何从父组件调用子组件中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56114356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com