RN與iOS還是有些差異性, 本人經(jīng)歷的一個情況是:在系統(tǒng)方法中無法調(diào)用自定義方法
代碼如下:
_renderItem(item){
if (item.section.key == 's3'){
if (item.item.key == 0){
return(
<View style={[styles.LastCellStyleView, {flexDirection: 'row-reverse',
alignItems: 'center'}]}>
{item.item.rightView}
<TextInput ref='textinput' style={styles.TextInputView}
onChangeText={(text)=>{
this.addRow();
}}
/>
</View>
)
}
}
addRow(txt){
this.setState({
data:2
})
}
場景是在cell中有一個TextInput, 要在內(nèi)容改變后就增動態(tài)增加一行,結(jié)果發(fā)現(xiàn)代碼中在SectionList中的_renderItem方法中, 無法調(diào)用addRow()自定義方法, 并且會報錯:
_this4.addRow is not a function
經(jīng)過修改, 發(fā)現(xiàn)及時使用常規(guī)的bind.this 方式也并不能解決, 因為此時_renderItem 是SectionList自動調(diào)用的方法,并不是當前類調(diào)用的, 所以此時this并不是指向當前類 無論你怎樣綁定,他都是指向SectionLIst 而SectionLIst并不含有自定義addRow方法,所以才會報錯
那怎樣才能將值傳出去呢, 后來想到了用通知的方法
所以, this.addRow
這里改為DeviceEventEmitter.emit('changeRMB',text)
而我們知道組件的生命周期, 在Render 方法調(diào)用后才會調(diào)用componentDidMount(){ }
所以我們在這里進行通知的接收,并且調(diào)用addRow方法:
componentDidMount() {
DeviceEventEmitter.addListener('changeRMB',this.addRow.bind(this))
}