我的代码有什么问题。为什么onclick事件句柄无法正常工作。
它没有显示任何控制台日志..我点击了整个元素
class App extends Component {
constructor(props) {
super(props);
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log("this Is clicked");
};
render(){
return (
<Singleimage onClick={this.handleClick} publicId= {this.props.publicId}>
</Singleimage>
);
}
}
如果你想看到SingleImage组件
import React , { Component } from 'react';
import PropTypes from 'prop-types';
import {CloudinaryContext, Transformation , Image} from 'cloudinary-react';
class Singleimage extends Component {
render(){
return (
<div>
<h1> cloudinary , {this.props.publicId}</h1>
<CloudinaryContext cloudName="demo">
<Image publicId= {this.props.publicId}>
<Transformation width="200" crop="scale" angle="10"/>
</Image>
</CloudinaryContext>
</div>
);
}
}
Singleimage.propTypes = {
publicId: PropTypes.string,
};
export default Singleimage;
答案 0 :(得分:1)
不使用on Singleimage
而是使用自定义道具handleClickProps
class App extends Component {
constructor(props) {
super(props);
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log("this Is clicked");
};
render(){
return (
<Singleimage handleClickProps={this.handleClick} publicId= {this.props.publicId} />
);
}
}
然后在您的子组件Singleimage
中,onClick调用道具handleClickProps
class Singleimage extends Component {
clickHandler(event){
this.props.handleClickProps(event.target)
}
render(){
return (
<div onClick={this.clickHandler.bind(this)} >
<h1> cloudinary , {this.props.publicId}</h1>
<CloudinaryContext cloudName="demo">
<Image publicId= {this.props.publicId}>
<Transformation width="200" crop="scale" angle="10"/>
</Image>
</CloudinaryContext>
</div>
);
}
}
希望这对你有所帮助。