繁体   English   中英

React Native:如何从父级的事件函数中调用子级引用?

[英]React Native : How to call child refs from the parent's event funtion?

尝试将父标记设为<TouchableWithoutFeedback>并将子标记设为<TouchableWithoutFeedback> <Image> ,尝试从父onPress函数更改图像源,但会出错。 如何使用ref存档? 或其他解决方法?

本机版本:0.56

错误:

Cannot read property 'favIcon' of undefined

样例代码:

const fav = require('../../images/favorite.png');
const nonfav = require('../../images/not_favorite.png');

updateFavorite = (id) => {
    this.props.refs.favIcon.source(fav);      
}

render(){
  return (
    <View style={styles.container}>                
       <TouchableWithoutFeedback onPress={ this.updateFavorite.bind(this, 1) }>
         <View style={ styles.imageView }>
           <Image refs="favIcon" source={ nonfav } />                   
         </View>
       </TouchableWithoutFeedback>
       <TouchableWithoutFeedback onPress={ this.updateFavorite.bind(this, 2) }>
         <View style={ styles.imageView }>
           <Image refs="favIcon" source={ nonfav } />                   
         </View>
       </TouchableWithoutFeedback>
   </View>
  )
}

注意 :仅更改onPressed的子图像,而不更改所有图像。

使用nativeProps试试,例如

import resolveAssetSource from 'resolveAssetSource';

this.refs['favIcon'].setNativeProps({
   src: [resolveAssetSource(fav)]
});

参照为多。

它可能不适用于机0.50+版本,但根据注释,它应适用于0.57.1

最好通过调用setState方法来完成React中元素的属性更新。 尝试以下

updateFavorite = (event) => {
  event.target.setAttribute('src', fav)
}

render(){
  return (
    <View style={styles.container}>       
       <TouchableWithoutFeedback>
         <View style={ styles.imageView }>
           <img ref={ref => this.favIcon = ref} src={nonFav} onPress={ this.updateFavorite }/>                   
         </View>
       </TouchableWithoutFeedback>         
       <TouchableWithoutFeedback>
         <View style={ styles.imageView }>
           <img ref={ref => this.favIcon = ref} src={nonFav} onPress={ this.updateFavorite } />                   
         </View>
       </TouchableWithoutFeedback>
   </View>
  )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM