#react-starter-kit 反应点击不触发页面

#react-starter-kit React onClick not firing on page

本文关键字:#react-starter-kit      更新时间:2023-09-26

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

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

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

如何在服务器端呈现后让 click 事件在客户端工作?

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

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

编辑 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指的是挂载的 DOM 组件,这不是您想要的。
  • 包装onClick to onClick={()=>this.handleClick()}是朝着正确方向迈出的一步,但还不够。 this现在指的是 react 组件,但不是指正确的组件。它是在.map函数中定义的,因此它指的是 colorSlice .这不是你想要的。

我的建议更进一步:

在 render 中,在 return 语句之前,添加以下行

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

并在映射函数内更改单击以:

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

希望这有帮助。

也许试试这个,

首先,创建一个包含这个的 var。 这应该发生在你的render()

var self = this;

然后在您的点击

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

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

希望它成功!

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

然后,在渲染函数中:

onClick={()=>this.handleClick()}