0
我有以下代碼中反應天然:React Native和Refs - 爲什麼此功能不會返回我的內容?
'use strict'
import React, { Component } from 'react';
import { AppRegistry, Animated, Dimensions, Easing, Image, Text, View, StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
const categoryTwoLinks = [
{ label: 'Subcategory1' },
{ label: 'Subcategory2' },
{ label: 'Subcategory3' },
{ label: 'Subcategory4' },
{ label: 'Subcategory5' },
{ label: 'Subcategory6' },
]
const categoryTouts = [
{ image: require('./assets/images/image01.jpg'), title: 'Category1' },
{ image: require('./assets/images/image02.jpg'), title: 'Category2', links: categoryTwoLinks },
{ image: require('./assets/images/image03.jpg'), title: 'Category3' },
]
class Tout extends Component {
render() {
console.log('tout')
return (
<Image
source={this.props.image}
ratioGrow
alignItems='center'
style={{ alignItems: 'center', justifyContent: 'center' }}
>
<Text
style={{ color: 'white', fontSize: 24, backgroundColor: 'transparent', fontWeight: 'bold' }}
>
{this.props.title}
</Text>
</Image>
)
}
}
export default class scrollAccordion extends Component {
handleScroll = ({ nativeEvent: { contentOffset } }: Object) => {
const scrollY = contentOffset.y
this.scrollOffsetValue.setValue(scrollY)
}
setScrollRef = node => {
console.log('set scroll ref')
if (node) {
this.scrollRef = node
}
}
renderCategoryTouts =() => {
console.log('render category tout')
categoryTouts.map((tout, index) => {
return (
<Tout
key={tout.title}
{...tout}
scrollViewRef={this.state.scrollRef}
scrollOffset={this.scrollOffsetValue}
/>
)
})
}
render() {
console.log('render')
let categoryTouts = this.scrollRef ? this.renderCategoryTouts() : null
return (
<View style={styles.container}>
<ScrollView
scrollEventThrottle={1}
ref={this.setScrollRef}
onScroll={this.handleScroll}
>
<View>
{categoryTouts}
</View>
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: 40,
backgroundColor: 'white',
},
toutText: {
color: 'white', backgroundColor: 'transparent', fontWeight: 'bold', fontSize: 24
}
});
AppRegistry.registerComponent('scrollAccordion',() => scrollAccordion);
未返回從renderCategoryTouts
功能的任何內容。
我知道最初this.scrollRef
是未定義的,所以主渲染函數將爲{categoryTouts}
變量返回{null}
。但scrollRef設置後,我需要它返回renderCategoryTouts
的結果。我如何得到這個工作?
- 我更新了這個代碼,包括什麼,我有一個完整的例子。如果我查看控制檯日誌,'render'將首先觸發,然後'setScrollRef',因此,'render category tout'根本不會觸發,因爲render方法從不重新觸發 – mheavers
這是正常行爲。在setScrollRef函數中,您尚未設置任何組件狀態。如果在此函數中使用setState,它將被重新渲染。在renderCategoryTouts函數中,你有this.state.scrollRef,但你從來沒有設置scrollRef的狀態。相反,你可以在setSCrollRef函數中使用this.scrollRef或setState組件(this.setState(scrollRef:node))。不要忘記在構造函數中綁定你的函數來調用this.setState或達到此目的。有趣的是,你在分配參考資料之後填寫內容,你應該檢查生命週期方法。 –