javascript - 反应包括一个 onClick 到一个跨度
问题描述
我想在我的跨度中包含一个 onClick 选项。
我有以下返回跨度的方法
setCondition = () => {
const condition = this.props.condition;
if(condition) {
return (
<div className="hidden-xs">
<span className="fa fa-thumbs-up fa-2x" style={{ backgroundColor: 'green' }} />
<span className="fa fa-thumbs-down fa-2x" />
</div>
);
} else {
return (
<div className="hidden-xs">
<span className="fa fa-thumbs-up fa-2x" />
<span className="fa fa-thumbs-down fa-2x" style={{ backgroundColor: 'red' }} />
</div>
);
}
}
当我单击其中一个跨度时,我想添加下面的方法。
const update = (cond) => {
console.log(cond);
}
我试着做:
<span onClick={this.update(true)} className="fa fa-thumbs-up fa-2x" style={{ backgroundColor: 'green' }} />
但是当我点击时它什么也没有发生。
解决方案
this.update(true)
绑定时不要调用函数。只绑定函数而不像this.update
.
<span onClick={this.update} className="fa fa-thumbs-up fa-2x" style={{ backgroundColor: 'green' }} />
检查React 文档中的示例。
如果需要传递固定参数,或者使用双箭头功能
const update = (cond) => () => {
console.log(cond);
}
<span onClick={this.update(true)} className="fa fa-thumbs-up fa-2x" style={{ backgroundColor: 'green' }} />
或者你可以使用匿名函数
const update = (cond) => {
console.log(cond);
}
<span onClick={this.update(true)} className="fa fa-thumbs-up fa-2x" style={{ backgroundColor: 'green' }} />
但正如文档所说:
这种语法的问题是每次 LoggingButton 呈现时都会创建不同的回调。
来源:reactjs.org
推荐阅读
- postgresql - 如何在 PostgreSQL 的 group by 子句中保留特定列中的一条记录并使其他记录值为 0?
- python - Find_next('table') BeautifulSoup
- java - 如何在Android App中实现触摸效果
- php - 使用 Laravel 5.8 的 PhpUnit
- css - WooCommerce Select2 Dropdown 默认排序过滤器颜色 CSS
- python - 用 python 编辑 .xlsx
- javascript - 身份验证安全反应
- winapi - 通过 GetRawInputBuffer 读取 RAWINPUT 时,WM_INPUT_DEVICE_CHANGE 消息会丢失
- instagram-graph-api - Instagram图形API,如何在不分页的情况下查询我帐户的所有媒体
- javascript - django 模板创建中的脚本错误