尽管绑定了这个,但是反应onClick不工作...不重复

时间:2017-11-04 05:57:18

标签: reactjs

我的代码有什么问题。为什么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;

1 个答案:

答案 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>
        );
    }
}

希望这对你有所帮助。