组件上的React Native ref /参考无法正常工作

时间:2019-06-15 20:18:07

标签: react-native react-ref

我正在开发React Native应用程序。我现在在应用程序中正在做的是尝试在组件上使用reference / ref。

这是我的代码

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

enter image description here

我也尝试过。

<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;

2 个答案:

答案 0 :(得分:0)

您正在使用被视为legacy and have some issue的字符串引用。

这是将new approachcreateRef一起使用的修改代码。

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;

答案 1 :(得分:0)

更改此

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

onPress={this._handleDownloadButton}