【问题标题】:#react-starter-kit React onClick not firing on page#react-starter-kit React onClick 没有在页面上触发
【发布时间】:2016-03-21 19:34:56
【问题描述】:

我正在使用 React-Starter-Kit,但遇到了 onClick={this.handleClick} 未在浏览器中触发的问题。

发生了什么: Colorswatches.js 组件正在加载并显示在浏览器中,但 onClick 不起作用。没有显示控制台日志。

我认为是问题所在: 将所有内容呈现在服务器端并传递给客户端,客户端会获得没有事件绑定的静态反应 html。

如何在服务器端渲染后让点击事件在客户端工作?

编辑:使用 jgldev 提供的示例更新代码

编辑 2:添加了 componentDidMount() 函数。使用控制台日志,仍然看不到页面加载日志

编辑 3:我发布的是 React-starter-kit 的另一部分,它正在轰炸客户端重新渲染。我将第一个答案标记为正确。

src/component/ColorSwatches/ColorSwatches.js:

import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ColorSwatches.scss';

class ColorSwatches extends Component {
    constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }
    componentDidMount() {
        console.log('I was mounted');
    }
    handleClick(){
        console.log('I was clicked');
    }
    render(){
        let colorSlices = this.props.colorSlices;
        let sku = this.props.sku;
        let currentSkuIndex = 0

        return (
            <div className='pdpColors'>
                <div className='colorSwatches' >
                    { colorSlices.map((colorSlice, index) => {
                        return (
                            <div title={colorSlice.color} onClick={()=>this.handleClick()}  key={index}>
                                <img src={colorSlice.swatchURL}/>
                            </div>
                        )
                    })}
                </div>
            </div>
        )
    }
}

export default withStyles(ColorSwatches,s);

【问题讨论】:

  • this.handleClick().bind(this) 不正确。试试this.handleClick.bind(this)
  • 啊,是的,这是一个错字。我的代码中有你的例子。我会编辑帖子
  • 你也不需要onClick中的额外箭头功能,你只需要onClick={this.handleClick}。它违背了将函数绑定到组件的目的,而是在每次渲染时创建一个新函数

标签: javascript reactjs react-starter-kit


【解决方案1】:

我的猜测是以下情况:

  • 原来this指的是挂载的DOM组件,这不是你想要的。
  • 将 onClick 封装到 onClick={()=&gt;this.handleClick()} 是朝着正确方向迈出的一步,但还不够。 this 现在指的是一个反应组件,但不是正确的。它在.map 函数中定义,因此它引用colorSlice。这不是你想要的。

我的建议更进一步:

在渲染内部,在您的 return 语句之前,添加以下行

let that = this; // this refers to ColorSwatches component, as intended

并在映射函数内部将onClick更改为:

onClick={that.handleClick}  // no need to add the wrapper now

希望这会有所帮助。

【讨论】:

  • 他使用的箭头函数不会创建它自己的“this”,而是使用组件的“this”
【解决方案2】:

也许试试这个,

首先创建一个包含这个的变量。这应该发生在您的render()

var self = this;

然后在您的 onClick 上

onClick={self.handleClick.bind(this)}

当我遇到这个问题时,这对我有用。

希望一切顺利!

【讨论】:

    【解决方案3】:

    在构造函数上: this.handleClick = this.handleClick.bind(this)

    然后,在渲染函数中:

    onClick={()=&gt;this.handleClick()}

    【讨论】:

    • 感谢您的回复。但是,这似乎仍然对我不起作用。没有控制台日志触发,什么都没有。
    • 也许 onClick 道具是 onclick?
    • 似乎没什么区别
    • 构造函数中的额外行似乎没有任何意义。您的绑定问题在渲染函数内部。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 2016-06-05
    • 2018-05-12
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多