reactjs - 仅在单击时使用参数调用函数的正确方法是什么?
问题描述
我试图通过传递来调用点击函数params
,但没有发生。页面加载后,我的所有函数都会被调用。
处理参数的正确方法是什么onClick
?
这是我的代码:
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
@inject("store")
@observer
class ToDoList extends Component {
constructor(props) {
super(props);
this.store = props.store;
this.todoName = React.createRef();
}
formHandler = e => {
e.preventDefault();
this.store.listUpdater(this.todoName.current.value);
e.target.reset();
};
showItem = item => {
console.log(item);
};
render() {
return (
<div>
<ul>
{this.store.Store.todo.map(item => (
<li onClick={this.showItem(item)}>{item}</li>
//calls on page loads.. looking to call only on click!!
))}
</ul>
<form onSubmit={this.formHandler}>
<div className="form-group">
<input type="text" ref={this.todoName} />
</div>
</form>
</div>
);
}
}
export default ToDoList;
解决方案
有几种方法,真的。
快速简单,但不太推荐:
就编程而言,此解决方案是最快的,因为它们都是单行的。它们的缺点是,每当您的组件重新渲染时,您都会生成一个新函数(就是这样() => ...
做的)。这通常不是什么大问题,但它可能会在较大的集合中为您的渲染引入一些额外的延迟。不过,通常这可以忽略不计。
<li onClick={() => this.showItem(item)}>{item}</li>
或者
<li onClick={this.showItem.bind(this, item)}>{item}</li>
更详细,但推荐:
推荐的方法是只定义一次函数及其参数。在这里,我们onClick
不会在每次重新渲染时获得一个新函数。相反,它有一个静态引用,this.click
它调用我们作为 prop 从父级传递的回调以及参数。
<MyListItem onClick={this.showItem} item={item} />
您将在哪里MyListItem
编写自定义组件。就像是:
class MyListItem extends React.Component {
constructor() {
super();
this.click = this.click.bind(this);
}
click() {
this.props.onClick(this.props.item);
}
render() {
return (
<li onClick={this.click}>{this.props.item}</li>
);
}
}
推荐阅读
- python - 在单独的图表中为 True/False 绘制布尔列
- python - Discord Bot 错误,延迟后不替换“毫秒”
- java - 如果有多个最大值,我如何在树图中找到按升序排列的键?
- html - Vue v-model 在历史前进,历史后退后中断
- javascript - 如何动画/绘制合并排序可视化?
- python-3.x - 如何在python中将2个输入列表相乘
- windows - 如何让 Snort 记录与给定规则匹配的数据包?
- sql - 为什么我会收到我的光标无效的错误消息?
- python - 如何更改 LogisticRegression 拟合函数的输入形状?
- java - flush() 方法生成 java.io.IOException: Relais brisé (pipe)