首页 > 解决方案 > 反应包括一个 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' }} />

但是当我点击时它什么也没有发生。

标签: javascripthtmlreactjs

解决方案


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


推荐阅读