【发布时间】:2018-05-15 07:21:43
【问题描述】:
我在 react 上遇到了 quill 编辑器的问题。imageHandler() 运行良好。
但在 imageHandler() 中,它也不能调用其他类型,如状态、道具、函数等.
我想在 module.toolbar.handlers 调用的imageHandler() 中调用 quillRef
下面是我的简单代码。
import React, { Component } from 'react';
import ReactQuill from 'react-quill'; // ES6
const formats = [
'header', 'font', 'size',
'bold', 'italic', 'underline', 'strike', 'blockquote',
'list', 'bullet', 'indent',
'link', 'image', 'video'
]
class App extends Component {
constructor(props) {
super(props)
this.state = { text: ''}
this.handleChange = this.handleChange.bind(this)
this.reactQuillRef = null; // ReactQuill component
this.quillRef = null; // Quill instance
}
modules = {
toolbar: {
container: [['bold', 'italic', 'underline', 'blockquote'],
[{'list': 'ordered'}, {'list': 'bullet'}],
['image'],
],
handlers: {
'image': this.imageHandler
}
}
}
componentDidMount() {
this.attachQuillRefs()
}
componentDidUpdate() {
this.attachQuillRefs()
}
attachQuillRefs = () => {
if (typeof this.reactQuillRef.getEditor !== 'function') return;
this.quillRef = this.reactQuillRef.getEditor();
}
imageHandler() {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
input.onchange = () => {
const file = input.files[0];
console.log(file); // works well
// problems : can't call ref, props, function... etc
console.log("ref : ", this.reactQuillRef, this.quillRef); // undefine
// this.insertImg(); // not work (insertImg is not a function)
console.log(this.props); // undefine
};
}
handleChange(value) {
this.setState({ text: value });
this.refs.test.innerHTML = this.state.text;
}
insertImg = () => {
console.log("insertImg",prototype);
var range = this.quillRef.getSelection();
let position = range ? range.index : 0;
console.log(this.quillRef); // works well!!!!!!!!! why diffrent with imgHandler()
this.quillRef.insertEmbed(position, 'image','https://images.pexels.com/photos/47480/pexels-photo-47480.jpeg?auto=compress&cs=tinysrgb&h=350');
}
render() {
return (
<div className="App">
<button onClick={this.insertImg}>Insert Img</button>
<ReactQuill value={this.state.text}
onChange={this.handleChange}
modules={this.modules}
formats={formats}
ref={(el) => {this.reactQuillRef = el}}
/>
<br/><br/>
<div contentEditable='true' ref='test'></div>
{this.state.text}
</div>
);
}
}
export default App;
我尝试了很多方法(都失败了),这种情况下,不起作用
imageHandler() {...} 到 imageHandler = () => {...}
我的 package.json 在这里
{
"name": "quill",
"version": "0.1.0",
"private": true,
"dependencies": {
"fine-uploader": "^5.16.2",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-quill": "^1.2.7",
"react-scripts": "1.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
知道为什么吗? 有人帮我把手吗? 谢谢!
【问题讨论】:
标签: javascript reactjs quill