Shu*_*tik 6 javascript reactjs quill react-quill
如何在react-quill中设置字符长度?在文档中, getLength() 将返回编辑器中字符的长度。
但我无法弄清楚如何实施它。
我的JSX
<ReactQuill theme='snow'
onKeyDown={this.checkCharacterCount}
value={this.state.text}
onChange={this.handleChange}
modules={modules}
formats={formats}
//style={{height:'460px'}}
/>
// OnChange Handler
handleChange = (value) => {
this.setState({ text: value })
}
//Max VAlue checker
checkCharacterCount = (event) => {
if (this.getLength().length > 280 && event.key !== 'Backspace') {
event.preventDefault();
}
}Run Code Online (Sandbox Code Playgroud)
上述解决方案是我在 GitHub 上找到的。但它不起作用...
小智 6
以下应该有效:
class Editor extends React.Component {
constructor (props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.quillRef = null; // Quill instance
this.reactQuillRef = null;
this.state = {editorHtml : ''};
}
componentDidMount() {
this.attachQuillRefs()
}
componentDidUpdate() {
this.attachQuillRefs()
}
attachQuillRefs = () => {
if (typeof this.reactQuillRef.getEditor !== 'function') return;
this.quillRef = this.reactQuillRef.getEditor();
}
handleChange (html) {
var limit = 10;
var quill = this.quillRef;
quill.on('text-change', function (delta, old, source) {
if (quill.getLength() > limit) {
quill.deleteText(limit, quill.getLength());
}
});
this.setState({ editorHtml: html });
}
render () {
return <ReactQuill
ref={(el) => { this.reactQuillRef = el }}
theme="snow"
onChange={this.handleChange}
value={this.state.editorHtml}
/>
}
}
Run Code Online (Sandbox Code Playgroud)
我相信您缺少对组件本身的引用ReactQuill。如果没有引用,您将无法访问其任何非特权方法(例如getLength())。您可以通过您的方法获取副本handleChange(https://github.com/zenoamaro/react-quill#props,即 onChange 属性上的第四个参数),但我建议您只需向组件添加一个单独的 ref 属性ReactQuill并使用它。请参阅下面重写为功能组件的示例(...自 2020 年以来已经):
export const Editor = () => {
const [value, setValue] = React.useState(null);
const reactQuillRef = React.useRef();
const handleChange = (value) => setValue(value);
const checkCharacterCount = (event) => {
const unprivilegedEditor = reactQuillRef.current.unprivilegedEditor;
if (unprivilegedEditor.getLength() > 280 && event.key !== 'Backspace')
event.preventDefault();
};
return (
<ReactQuill theme='snow'
onKeyDown={checkCharacterCount}
ref={reactQuillRef}
value={this.state.text}
onChange={this.handleChange}
modules={modules}
formats={formats} />
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11416 次 |
| 最近记录: |