Skip to content

Commit 841a9e3

Browse files
a1oohajaywcjlove
authored andcommitted
Fix: handle event with latest props
1 parent 1f228f1 commit 841a9e3

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

src/index.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@ function ReactCodeMirror(props = {}, ref) {
1717
const { options = {}, value = '', width = '100%', height = '100%' } = props;
1818
const [editor, setEditor] = useState();
1919
const textareaRef = useRef();
20+
const lastestProps = useRef(props);
21+
2022
useImperativeHandle(ref, () => ({ editor }), [editor]);
23+
lastestProps.current = props;
24+
2125
// 将props中所有的事件处理函数映射并保存
2226
function getEventHandleFromProps() {
2327
const propNames = Object.keys(props);
@@ -60,7 +64,7 @@ function ReactCodeMirror(props = {}, ref) {
6064
const instance = CodeMirror.fromTextArea(textareaRef.current, {...defaultOptions, ...options});
6165
const eventDict = getEventHandleFromProps();
6266
Object.keys(eventDict).forEach((event) => {
63-
instance.on(eventDict[event], props[event]);
67+
instance.on(eventDict[event], (...params) => lastestProps.current[event](...params));
6468
});
6569
instance.setValue(value || '');
6670

@@ -103,4 +107,4 @@ function ReactCodeMirror(props = {}, ref) {
103107
);
104108
}
105109

106-
export default React.forwardRef(ReactCodeMirror);
110+
export default React.forwardRef(ReactCodeMirror);

0 commit comments

Comments
 (0)