javascript - 如何将事件添加到反应功能和重新渲染功能
问题描述
我有一个函数可以根据 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 事件在页面上重新输出函数?
解决方案
在不涉及上下文和键的复杂性的情况下,组件需要更改道具或状态才能重新渲染。要阅读有关状态和组件生命周期的更多信息,文档对类组件有很好的解释。
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
是副作用和异步行为的更可取的生命周期函数。值得庆幸的是,文档有很多细节!
推荐阅读
- javascript - Date.getTime 不是节点中的函数?
- jsf - 如何在选择之后和上传之前从 p:fileUpload 获取选定的文件
- excel - CSE 公式对应用于所有行的复杂公式的结果求和
- ios - 在 UILabel 特定字符后面画圆圈
- c# - 运行 SPR 时,ExecuteReader 不支持获取 MultiExec
- excel - 如何根据组合框选择在文本框上显示文本
- ethereum - 通过 new 创建实例时调用方法在另一个合约中失败
- python - 在 Python 中创建和使用图像缩略图
- regex - 使用正则表达式根据包含反斜杠的字段值查询文档
- database - 如何在 Firebase 实时数据库上建模聊天应用程序?