首页 > 解决方案 > 如何将事件添加到反应功能和重新渲染功能

问题描述

我有一个函数可以根据 API 数据填充的状态将内容呈现到页面,但我需要一个 onClick 事件来优化该内容;

所以目前 getPosts 从状态“帖子”返回信息,这些信息由我们的 API 提供的数据提供,但我想进一步过滤这些内容,所以我的想法是有某种事件监听器,如果采取行动,改变数据出来的getPosts。

constructor() {
    super();
    this.state = {
        posts: ""
    }
    this.getPosts = this.getPosts.bind(this);
}
async componentWillMount(){
    var data = await api.posts();
    this.setState({posts: data.data});
    console.log(this.state.posts);
}
getPosts(type){
        if(this.state.posts.length){
            return this.state.posts.map((content,index) => {
                var url = content.Title.replace(/[^\w\s]/gi, '');
                url = url.replace(/\s+/g, '-').toLowerCase();
                if(type === content.PostType){
                    //output something different
                }
                else{
                    return(
                        <Col md={4} className="mb-4" key={index}>
                            {content.title}
                        </Col>
                    );
                }
            })

        }
    }
    render() {
        return (
            <div>
            <p><button onClick={()=>{this.getPosts('blog')}}>blog</button> <button onClick={()=>{this.getPosts('news')}}>news</button></p>
            {this.getPosts()}
            </div>
        )
    }

所以我的 getPosts 没有任何类型就可以正常工作,如何告诉它根据 onClick 事件在页面上重新输出函数?

标签: javascriptreactjsdom-events

解决方案


在不涉及上下文和键的复杂性的情况下,组件需要更改道具或状态才能重新渲染。要阅读有关状态和组件生命周期的更多信息,文档对类组件有很好的解释。

onClick您的组件在事件处理程序调用后不会重新渲染,getPosts因为getPosts不会更新内部组件状态。getPosts在渲染中工作,因为这些值正在返回给 React。通过getPosts用作onClick事件处理程序,您正在创建 React 元素并尝试将它们返回到窗口。

以下内容应视为伪代码,显示如何触发您的组件以呈现不同的帖子:

  • 考虑在构造函数中添加另一个状态键,
constructor(props) {
  super(props);
  this.state = {
    posts: "",
    type: null
  };
  this.getPosts = this.getPosts.bind(this);
  this.onClick = this.onClick.bind(this);
}
  • 并创建一个不尝试返回 React 元素的点击处理程序
function onClick(evt) {
  this.setState({ type: evt.target.value });
}
  • 和按钮的值
<button onClick={this.onClick} type="button" value="blog">blog</button>
  • 现在您的按钮将使用您的新帖子类型更新状态,从而导致您的组件重新渲染:
render() {
  return (
    <div>
      <p>
        <button onClick={this.onClick} type="button" value="blog">blog</button>
        <button onClick={this.onClick} type="button" value="news">news</button>
      </p>
      {this.getPosts()}
    </div>
  );
}

随着内容类型被存储在状态中,您现在可以getPosts以任何适合您的方式实现您的调用。祝你好运!

它偏离了所提出的问题,但值得注意componentWillMount的是已被弃用,并且componentDidMount是副作用和异步行为的更可取的生命周期函数。值得庆幸的是,文档有很多细节!


推荐阅读