React Native点击保存按钮报n._viewer.saveDocument未定义错误如何解决
问题根因
- 最直接的错误是你给
DocumentView绑定ref的代码被注释了,this._viewer从未被赋值,自然调用saveDocument方法时会报undefined错误 - filepath赋值逻辑存在缺陷,且异常分支的提示代码完全不生效,也可能引发后续加载、保存异常
- 调用实例方法前没有做兼容判断,极端场景下也会报错
- React Native不支持
h1这类Web标签,你写的异常提示代码本身也不符合语法规范
具体修复方案
- 取消ref代码的注释,给
this._viewer正常赋值 - 修正filepath的赋值逻辑和异常分支的返回逻辑,你原来else分支里的
<h1>代码写了但没返回,完全不生效,要把异常情况的UI正常返回,同时替换为React Native支持的Text组件 - 调用
saveDocument前先判断this._viewer是否存在,避免报错
修复后参考代码
import { Text } from 'react-native' // ...其他代码省略 render() { if (this.props.dsType == "fileDocument") { let filepath; if (path == fileContent.value) { filepath = path.uri; console.info("filepath =", filepath); return ( <View style={{ flex: 1 }}> <DocumentView ref={(c) => this._viewer = c} document={filepath} onDocumentLoaded={path => { console.info("The document has finished loading:", path); }} /> <View style={styles.button}> <Button onPress={() => { // 先判断实例存在再调用方法 this._viewer?.saveDocument().then((filePath) => { console.log('saveDocument:', filePath); }).catch(err => console.log('保存失败', err)); }} title="Save" /> </View> </View> ); } else { // 异常情况正常返回提示UI return <Text>Unable to render document.</Text>; } } return null; }
内容的提问来源于stack exchange,提问作者Elvisworld
相关产品推荐
相关产品推荐

