首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么在SubText中不触发onLayout?

为什么在SubText中不触发onLayout?
EN

Stack Overflow用户
提问于 2018-06-20 02:27:00
回答 2查看 551关注 0票数 4

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

A代码

代码语言:javascript
复制
<View>
  <Text>
    <Text onLayout={e => {console.log("this isn't triggered!")}}>{"foo"}</Text>
  </Text>
</View>

B代码

代码语言:javascript
复制
<View>
  <Text onLayout={e => {console.log("here the event it is called, but I need call in a SubText")}}>{"foo"}</Text>
</View>
EN

回答 2

Stack Overflow用户

发布于 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

代码语言:javascript
复制
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函数被调用了!

票数 2
EN

Stack Overflow用户

发布于 2018-06-28 01:19:24

我在RN repo上发现了这个相关的bug:https://github.com/facebook/react-native/issues/11650。仍在寻找一种测量嵌套文本的方法

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50934786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档