我做了以下应用程序: 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 $