#react-starter-kit 反应点击不触发页面
#react-starter-kit React onClick not firing on page
我正在使用 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()}
- React重新渲染但未显示正确的组件
- React组件等待所需道具进行渲染
- React中的数据集表示
- Webpack开发服务器和React服务器端渲染
- React Redux错误页面管理
- react.js中的密钥绑定
- 如何在react js中将值从一个组件发送到另一个组件
- React Native通过Navigator将用户输入数据传递到选项卡栏IOS中的组件
- React:按键的性能提升
- 如何在react js中从一个页面导航到另一个页面
- React组件-设置页面标题
- 为react组件传递道具的最佳方式
- 如何使用带有Preact的React路由器
- 使用Jest测试React Native应用程序
- 为什么我的点击事件没有使用 react js 触发
- React 15使用空字符串删除输入值
- #react-starter-kit 反应点击不触发页面
- React Starter Kit中路由和组件的角色
- 如何使用OpenLayers与react-starter-kit
- React Starter Kit:为客户端引入常量