[英]React Native ref to element is undefined in flatlist item
I am trying to get a ref to an element whilst rendering a flatlist but the ref is coming back as undefined. 我正在尝试在呈现平面列表的同时获取对元素的引用,但是该引用返回为未定义。 See relevant code below:
请参阅下面的相关代码:
Constructor: 构造函数:
constructor(props) {
super(props);
this.modalRef = createRef();
}
RenderItem: RenderItem:
_renderItem = ({ item }, context) => {
const modalRef = context.modalRef.current; // Why is context.modalRef.current null?
let onPress = () => alert("Something went wrong...");
return (
<View style={styles.item}>
<ListItemCard
id={item.id}
value="Some value.."
onPress={onPress()}
/>
</View>
);
};
Within Render function: 在渲染功能内:
Modal on screen: 屏幕上的模态:
<Modal
ref={this.modalRef}
text="Some text.."
onPressClose={() =>
this.modalRef.current.close()
}
/>
Flatlist: Flatlist:
<FlatList
data={data}
renderItem={item => this._renderItem(item, this)}
keyExtractor={(item, index) => index.toString()}
/>
modalRef.current
is null
because the reference is assigned on mount of the Modal
component. modalRef.current
为null
因为该引用是在安装Modal
组件时分配的。 I assume that the component is not mounted at the time the _renderItems
function is called. 我假定在调用
_renderItems
函数时未安装该组件。
I recommend that you use the ref inside a function that does not render a component, for example an event handler. 我建议您在不呈现组件的函数(例如事件处理程序)中使用ref。 There the
ref
variable should have a reference to the component. ref
变量应在其中引用该组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.