react-native - 组件上的 React Native ref/reference 不起作用
问题描述
我正在开发一个 React Native 应用程序。我现在在我的应用程序中所做的是我试图在我的组件上使用引用/引用。
这是我的代码
class Gallery extends React.Component {
constructor(props) {
super(props);
}
_handleDownloadButton = () => {
var uri = this.refs.logoImage.props.source;
var promise = CameraRoll.saveImageWithTag(uri);
promise.then(function(result) {
console.log('save succeeded ' + result);
Alert.alert('Saved')
}).catch(function(error) {
console.log('save failed ' + error);
Alert.alert('Error')
});
}
render() {
return (
<View>
<Button
onPress={() => {
this._handleDownloadButton();
}}
title="Download photo">
</Button>
<Image ref="logoImage" style={{ width: 100, height: 100 }} source={{ uri: 'https://static.standard.co.uk/s3fs-public/thumbnails/image/2016/05/22/11/davidbeckham.jpg?w968' }} />
</View>
);
}
}
export default Gallery;
当我单击下载按钮时,出现以下错误。
Cannot find property source of undefined
我也试过这个。
<Image ref={ref => this.image = ref} style={{ width: 100, height: 100 }} source={{ uri: 'https://static.standard.co.uk/s3fs-public/thumbnails/image/2016/05/22/11/davidbeckham.jpg?w968' }} />
和
var uri = this.image.props.source;
我得到了同样的错误。我也试过这个。
在我添加的构造函数中
this.image = React.createRef();
零件
<Image ref={this.image} style={{ width: 100, height: 100 }} source={{ uri: 'https://static.standard.co.uk/s3fs-public/thumbnails/image/2016/05/22/11/davidbeckham.jpg?w968' }} />
和
var uri = this.image.props.source;
解决方案
您正在使用被认为是旧的并且有一些问题的字符串引用。
这是您如何使用新方法的修改后的代码createRef
。
class Gallery extends React.Component {
constructor(props) {
super(props);
this.image = createRef();
}
_handleDownloadButton = () => {
const imageRef = this.image.current;
if (imageRef) {
const url = imageRef.props.source;
}
}
render() {
return (
<View>
<Image ref={this.image} style={{ width: 100, height: 100 }} source={{ uri: 'https://static.standard.co.uk/s3fs-public/thumbnails/image/2016/05/22/11/davidbeckham.jpg?w968' }} />
</View>
);
}
}
export default Gallery;
推荐阅读
- asp.net - IdentityServer4 SPA登录
- javascript - 在深度嵌套的 JSON 中查找具有特定名称的所有键
- javascript - 如何避免 React.js 中的 useEffect 和 useCallback 依赖循环
- charts - 我试图在折线图中显示我的数据,但我无法转换我的数据类型。到 int 和 LocalDateTime
- python - 当我指定相同的宽度时,为什么我的水平条形图中的条具有不同的宽度?
- combinations - 有大小限制的项目组合
- python - 为什么 time.sleep(...) 不受 GIL 影响?
- image - 在 Laravel 中处理来自 Dropzone 的文件块
- angular - 带有 apollo-angular 客户端的 Aws-appsync 订阅
- svm - 文档长度可以用作分类的特征吗?