簡體   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