JCrop with React 使用自定义脚本加载 jquery 对象:TypeError: a is undefin



我做了以下应用程序: https://github.com/pc-magas/reaqct-jcrop

我有以下组件,我想在其中使用 jcrop:

import React, { Component } from 'react';
import $ from './MyJquery.js';
import Jcrop from 'jcrop';

class JCrop extends Component {
constructor(props){
super(props)
this.state={
'imageToCrop':props.imageToCrop,
'imageHtmlElement':null
}
}
comonentDidMount() {
$("#img").Jcrop();
}
render(){
return(
<img id="img" rel={ (rel) => {this.setState({imageHtmlElement:rel})} } src={ this.state.imageToCrop } />
)
}
}
export default JCrop

我还创建了./MyJquery.js以便将 Jquery 对象应用于窗口:

import $,{jQuery} from 'jquery';
window.jQuery = jQuery;
export default $

但是当我通过 npm run 运行应用程序时,出现以下错误:

类型错误:a 未定义

我该如何解决它?

我认为您应该将componentWillMount更改为componentDidMount
在您的情况下,当您尝试Jcrop时,#img元素尚不存在。

您的问题是window.jQuery不包含正确的对象。它必须具有$objext 而不是 jQuery 对象。所以./MyJquery.js应该是:

import $ from 'jquery';
window.jQuery = $;
export default $

最新更新