{"foo"} B代码 {con-6ren">
gpt4 book ai didi

react-native - 为什么 onLayout 不在 SubText 中触发?

转载 作者:行者123 更新时间:2023-12-03 19:34:54 28 4
gpt4 key购买 nike

我有一个关于 onLayout 事件的问题

一个代码

<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>

最佳答案

这是后代的答案。在我找到答案之前,我已经通过了这里,所以也许这会对其他人有所帮助。
就我而言,我需要在 ScrollView 中显示属性文本,并能够滚动到文本中的不同子字符串。
Nesting texts within texts creates a single NSAttributedString behind the scenes on iOS and a SpannableString on Android ,因此尝试添加 onLayout嵌套文本元素的 prop 实际上没有任何效果,因为它实际上并未在结果 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= 的行上遇到 Typescript 错误。支柱。谷歌搜索解决方案并没有发现任何问题,但调用了 prop 函数!

关于react-native - 为什么 onLayout 不在 SubText 中触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50934786/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com