英文:
Why I cannot create my own custom hook in js?
问题
这是您的代码的中文翻译:
我试图将我的编辑器制作成一个自定义钩子,所以我创建了名为'useEditor'的钩子,如下所示:
import { useState, useEffect } from 'react';
import ReactQuill from 'react-quill';
import MathEditor from './MathEditor';
// 其他一些导入
function useEditor() {
const [editorHtml, setEditorHtml] = useState('');
const [placeholder, setPlaceholder] = useState('写点什么...');
const [mathEditorVisible, setMathEditorVisible] = useState(false);
const [expressionEditable, setExpressionEditable] = useState(false);
const handleChange = (html) => {
setEditorHtml(html);
};
// 其他一些函数
const Editor = () => (
<div>
<ReactQuill
onChange={handleChange}
value={editorHtml}
modules={modules}
bounds='.app'
placeholder={placeholder}
/>
{mathEditorVisible && (
<MathEditor
onSaveFormula={handleSaveFormula}
setMathEditorVisible={setMathEditorVisible}
expressionEditable={expressionEditable}
setExpressionEditable={setExpressionEditable}
initialLatex=''
/>
)}
</div>
);
return {
Editor,
handleChange
};
}
export default useEditor;
但在编译时出现以下错误:
*** 对象不被视为有效的React子元素(找到了具有键{Editor, handleChange}的对象)。如果您打算呈现一组子元素,请改用数组。 ***
英文:
I was trying to make my Editor a custom hook so I created 'useEditor' hook like this
import { useState, useEffect } from 'react';
import ReactQuill from 'react-quill';
import MathEditor from './MathEditor';
//some other imports
function useEditor() {
const [editorHtml, setEditorHtml] = useState('');
const [placeholder, setPlaceholder] = useState('Write something...');
const [mathEditorVisible, setMathEditorVisible] = useState(false);
const [expressionEditable, setExpressionEditable] = useState(false);
const handleChange = (html) => {
setEditorHtml(html);
};
//some other functions
const Editor = () => (
<div>
<ReactQuill
onChange={handleChange}
value={editorHtml}
modules={modules}
bounds='.app'
placeholder={placeholder}
/>
{mathEditorVisible && (
<MathEditor
onSaveFormula={handleSaveFormula}
setMathEditorVisible={setMathEditorVisible}
expressionEditable={expressionEditable}
setExpressionEditable={setExpressionEditable}
initialLatex=''
/>
)}
</div>
);
return {
Editor,
handleChange
};
}
export default useEditor;
But when compiling this error occurs
*** Objects are not valid as a React child (found: object with keys {Editor, handleChange}). If you meant to render a collection of children, use an array instead. ***
答案1
得分: 1
你没有导出Editor
,你导出的是useEditor
。你必须调用useEditor
来获取Editor
。
import useEditor from './components/useEditor';
function App() {
const { Editor } = useEditor();
return (
<div className='app'> <Editor /> </div>
);
}
英文:
You are not exporting Editor
, you are exporting useEditor
. You have to call useEditor
to get Editor
import useEditor from './components/useEditor';
function App() {
const { Editor } = useEditor();
return (
<div className='app'> <Editor /> </div>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论