React Native中TextInput无法根据初始内容设置初始高度问题问询
问题根因
onContentSizeChange 回调仅会在输入框内容发生交互变更时触发,首次渲染传入defaultValue不属于内容变更事件范畴,因此不会触发你写的高度更新逻辑,导致初始高度异常。
可行解决方案
方案1:删除手动高度控制,使用原生自适应能力(最优)
React Native 0.60+ 版本的多行TextInput本身支持高度自适应,只要不写死高度,设置height: undefined+最小高度即可,无需手动监听onContentSizeChange维护高度状态:
<TextInput defaultValue={inputDescription} multiline={true} onChangeText={e => setInputDescription(e)} // 只保留最小高度限制,height设为undefined让组件自动撑开 style={[Style.descriptionInput, { minHeight: 40, height: undefined }]} placeholder={'Take a note'} placeholderTextColor={'black'} />
方案2:挂载后手动触发高度计算
如果需要兼容旧版本RN,必须手动维护高度状态,可以通过ref在组件挂载完成后主动读取内容高度更新状态:
import { useRef, useEffect } from 'react'; // 组件内声明TextInput引用 const textInputRef = useRef(null); // 初始值加载完成后主动计算高度 useEffect(() => { if (textInputRef.current && inputDescription) { // 主动触发一次高度更新 textInputRef.current.measure((x, y, width, contentHeight) => { setDescriptionHeight(contentHeight); }); } }, [inputDescription]); // 给TextInput绑定ref <TextInput ref={textInputRef} defaultValue={inputDescription} multiline={true} onChangeText={e => setInputDescription(e)} style={[Style.descriptionInput, { height: descriptionHeight }]} onContentSizeChange={e => setDescriptionHeight(e.nativeEvent.contentSize.height) } placeholder={'Take a note'} placeholderTextColor={'black'} />
方案3:改用受控模式触发高度更新
将defaultValue替换为受控属性value,初始值变更会被识别为内容更新,自动触发onContentSizeChange回调:
<TextInput // 替换defaultValue为受控value value={inputDescription} multiline={true} onChangeText={e => setInputDescription(e)} style={[Style.descriptionInput, { height: descriptionHeight }]} onContentSizeChange={e => setDescriptionHeight(e.nativeEvent.contentSize.height) } placeholder={'Take a note'} placeholderTextColor={'black'} />
内容的提问来源于stack exchange,提问作者Gaurav Thakur
相关产品推荐
相关产品推荐

