首页 > 解决方案 > 在 React Native 中使用 Text numberOfLines 道具时正确显示更多/更少

问题描述

我想使用 React Native 中的 comp 及其 props 根据文本的内容长度正确显示显示/隐藏numberOfLines

目前我已经尝试过这样的东西,但它没有按预期工作:

const postTextContent = (props) => {
const [textShown, setTextShown] = useState(false); //To show ur remaining Text
const [lengthMore,setLengthMore] = useState(false); //to show the "Read more & Less Line"
const toggleNumberOfLines = () => { //To toggle the show text or hide it
    setTextShown(!textShown);
}

const onTextLayout = useCallback(e =>{
    setLengthMore(e.nativeEvent.lines.length >=3);
},[]);
    
  return (
      <View style={styles.mainContainer}>
          <Text
              onTextLayout={onTextLayout}
              numberOfLines={textShown ? undefined : 3}
              style={{ lineHeight: 21 }}>{Your Long Text}</Text>

              {
                  lengthMore ? <Text
                  onPress={toggleNumberOfLines}
                  style={{ lineHeight: 21, marginTop: 10 }}>{textShown ? 'Read less...' : 'Read more...'}</Text>
                  :null
              }
      </View>
  )
}

上面的问题是,当文本等于 3 行时,Read More 文本会显示,这是不应该的,因为没有超过 3 行的文本。

知道如何处理这种情况吗?

标签: javascriptreactjsreact-native

解决方案


推荐阅读