2017-02-18 106 views
1

我正嘗試使用map函數爲每個組件創建一個ref反應原生。無法在地圖功能中設置參考

這是我的組件:

class Foo extends Component { 

constructor(props) { 
    super(props) 
} 

render() { 
    return (
    <ScrollView> 
    {this.state.barList.map(createSlides)} 
    </ScrollView> 
) 
} 

const createSlides = (uri, i) => (<CarouselItem 
         onPress={() => {}} 
         imgUrl={uri} 
         itemWidth={carouselItemWidth} 
         padding={carouselItemPadding} 
         key={i} 
         ref={(slide) => { this['slide_' + i] = slide}} 
         />); 

正如你看到的,我設置一個ref,但後來嘗試訪問ref的IT讓我undefined時。我的錯誤在哪裏?

+1

'createSlides'沒有看到的範圍('this')的createSlides方法類的。 –

回答

1

嘗試把你的Component

class Foo extends Component { 

    constructor(props) { 
    super(props) 
    // make sure this method gets the right scope, no matter how it's called 
    this.createSlides = this.createSlides.bind(this) 
    } 

    render() { 
    return (
     <ScrollView> 
     {this.state.barList.map(this.createSlides)} 
     </ScrollView> 
    ) 
    } 

    createSlides(uri, i) { 
    return (<CarouselItem 
     onPress={() => { }} 
     imgUrl={uri} 
     itemWidth={carouselItemWidth} 
     padding={carouselItemPadding} 
     key={i} 
     ref={(slide) => { this['slide_' + i] = slide }} 
    />) 
    } 
} 
+0

謝謝指出我愚蠢的錯誤:)) – Edgar