0

我正在开发一个 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;
4

2 回答 2

0

您正在使用被认为是旧的并且有一些问题的字符串引用。

这是您如何使用新方法的修改后的代码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;
于 2019-06-16T01:34:21.413 回答
-1

改变这个

 onPress={() => {
          this._handleDownloadButton();
        }}

onPress={this._handleDownloadButton}             
于 2019-06-16T09:35:16.133 回答