【发布时间】: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