如何在React的Ketcher编辑器组件中获取结构属性?
获取Ketcher编辑器中的分子结构
你可以通过以下两种方式获取编辑器内的分子结构并同步到React状态中:
方式一:自动监听结构变化
通过useRef获取Editor组件实例,订阅编辑器的change事件,每当分子结构修改时自动更新状态:
import { useState, useRef, useEffect } from "react" import { StandaloneStructServiceProvider } from "ketcher-standalone" import { Editor } from "ketcher-react" import "ketcher-react/dist/index.css" const structServiceProvider = new StandaloneStructServiceProvider() const KetcherEditor = () => { const [structure, setStructure] = useState('') const editorRef = useRef(null) useEffect(() => { if (!editorRef.current) return // 订阅结构变化事件 const unsubscribe = editorRef.current.editor.subscribe('change', async () => { // 获取当前结构对象 const struct = await editorRef.current.editor.getStructure() // 转换为SMILES格式(可根据需求换成toMol、toInChI等) const formattedStruct = await structServiceProvider.structService.toSmiles(struct) setStructure(formattedStruct) }) // 组件卸载时取消订阅 return () => unsubscribe() }, []) return( <div> <Editor ref={editorRef} staticResourcesUrl="" structServiceProvider={structServiceProvider} errorHandler={message => console.error(message)} /> <p>当前结构(SMILES):{structure}</p> </div> ) } export default KetcherEditor
方式二:手动触发获取
适合需要在特定时机(比如用户点击保存按钮)获取结构的场景:
import { useState, useRef } from "react" import { StandaloneStructServiceProvider } from "ketcher-standalone" import { Editor } from "ketcher-react" import "ketcher-react/dist/index.css" const structServiceProvider = new StandaloneStructServiceProvider() const KetcherEditor = () => { const [structure, setStructure] = useState('') const editorRef = useRef(null) // 手动获取结构的函数 const fetchCurrentStructure = async () => { if (!editorRef.current) return const struct = await editorRef.current.editor.getStructure() // 转换为你需要的格式,这里以Mol文件为例 const molStruct = await structServiceProvider.structService.toMol(struct) setStructure(molStruct) // 这里可以添加存储或其他业务逻辑 console.log('当前分子结构(Mol):', molStruct) } return( <div> <Editor ref={editorRef} staticResourcesUrl="" structServiceProvider={structServiceProvider} errorHandler={message => console.error(message)} /> <button onClick={fetchCurrentStructure}>获取并保存结构</button> <pre>{structure}</pre> </div> ) } export default KetcherEditor
关键说明:
- 通过
editorRef.current.editor可以访问Ketcher的底层编辑器实例,调用getStructure()获取结构对象 - 借助
structServiceProvider可以将结构对象转换为多种格式:- SMILES:
toSmiles(struct) - Mol文件:
toMol(struct) - InChI:
toInChI(struct)
- SMILES:
- 自动监听方式中的
subscribe('change', ...)会在结构每次修改时触发,确保状态与编辑器内容实时同步
内容的提问来源于stack exchange,提问作者user21101711
相关产品推荐
相关产品推荐

