【问题标题】:How to make multiline TextInput shrink when deleting lines (React-Native)?删除行时如何使多行TextInput缩小(React-Native)?
【发布时间】:2021-05-29 09:41:50
【问题描述】:

我有一个自定义的多行 TextInput,它会自动增长/扩展以适应其内容:

    import React, { useState } from 'react'
    import { TextInput } from 'react-native'
    
    export function MyInput() {
        const [value, setValue] = useState('Sample')
        const [height, setHeight] = useState(56)
        return (
            <TextInput
                value={value}
                onChangeText={text => {
                    setValue(text)
                }}
                onContentSizeChange={event => {
                    setHeight(Math.max(56, event.nativeEvent.contentSize.height))
                }}
                multiline
                style={{
                    padding: '16px',
                    height: height + 'px'
                }}
            />
        )

}

但是,如果它已经扩展到多行并且我删除了它的内容,onContentSizeChange 不会触发并且空行不会自动删除。有任何解决这个问题的方法吗?谢谢!

【问题讨论】:

    标签: reactjs react-native frontend textinput react-native-textinput


    【解决方案1】:

    我找到了两种缩小输入的方法:

    1. 在 style props 中为TextInput 添加边框,例如:
    borderWidth: 0.5, // any value is required
    borderColor: "transparent"
    
    1. 使用onChange 回调而不是TextInput 中的onContentSizeChange(最初发布here):
    onChange={(e) => {
      e.nativeEvent.target.style.height = 0;
      e.nativeEvent.target.style.height = `${e.nativeEvent.target.scrollHeight}px`;
    }}
    

    【讨论】:

      猜你喜欢
      • 2017-11-09
      • 2021-11-01
      • 2021-05-25
      • 2019-01-10
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      相关资源
      最近更新 更多