我有一个关于onLayout事件的问题
A代码
<View>
<Text>
<Text onLayout={e => {console.log("this isn't triggered!")}}>{"foo"}</Text>
</Text>
</View>B代码
<View>
<Text onLayout={e => {console.log("here the event it is called, but I need call in a SubText")}}>{"foo"}</Text>
</View>发布于 2020-09-09 06:49:41
这是给子孙后代的答案。在找到我的答案之前,我在这里滚动了一遍,所以这可能会对其他人有所帮助。
在我的例子中,我需要在滚动视图中显示属性文本,并且能够滚动到文本中的不同子字符串。
Nesting texts within texts creates a single NSAttributedString behind the scenes on iOS and a SpannableString on Android,所以尝试向嵌套的文本元素添加onLayout属性实际上没有任何效果,因为在生成的DOM中,它实际上不会表示为自己的文本元素。
在我的例子中,解决方案是use the onTextLayout prop of the Text component
import React from "react"
import { StyleSheet, ScrollView, Text, View } from "react-native"
const App = () => {
const scrollViewRef = React.useRef<ScrollView>(null)
const onTextLayout = React.useCallback(event => {
const scrollLocation = event.nativeEvent.lines.find(
line => line.text === "6. Hello\n",
).y
if (scrollViewRef.current) {
scrollViewRef.current.scrollTo({
x: 0,
y: scrollLocation,
animated: true,
})
}
}, [])
return (
<View style={styles.container}>
<View style={{ height: 100 }}>
<ScrollView
ref={scrollViewRef}
style={{
width: 100,
height: 100,
borderColor: "#000",
borderWidth: 1,
}}
>
<Text onTextLayout={onTextLayout}>
<Text>1. Hello{"\n"}</Text>
<Text>2. Hello{"\n"}</Text>
<Text>3. Hello{"\n"}</Text>
<Text>4. Hello{"\n"}</Text>
<Text>5. Hello{"\n"}</Text>
<Text>6. Hello{"\n"}</Text>
<Text>7. Hello{"\n"}</Text>
<Text>8. Hello{"\n"}</Text>
<Text>9. Hello{"\n"}</Text>
<Text>10. Hello{"\n"}</Text>
<Text>10. Hello{"\n"}</Text>
<Text>10. Hello{"\n"}</Text>
<Text>10. Hello{"\n"}</Text>
</Text>
</ScrollView>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
})
export default App顺便说一句,我在使用onTextLayout=属性的代码行上遇到了打字错误。谷歌搜索解决方案没有找到任何结果,但prop函数被调用了!
发布于 2018-06-28 01:19:24
我在RN repo上发现了这个相关的bug:https://github.com/facebook/react-native/issues/11650。仍在寻找一种测量嵌套文本的方法
https://stackoverflow.com/questions/50934786
复制相似问题