[React Native]TextInput超出部分文字高亮

React Native logo

是 Threads 和 X 上的功能,當輸入的內容超出字數限制,超出的部分會高亮顯示(文字有棕色底色):

image 1

要實現這個功能也挺簡單的,只需要在 TextInput 中包兩層 Text,將沒超過和超過的文字內容分開顯示就好。

const [text, setText] = useState('');
const MAX_CHARACTERS = 200; // 最大字數限制
const characterCount = text.length;
const isOverLimit = characterCount > MAX_CHARACTERS;
const overLimitCount = isOverLimit ? characterCount - MAX_CHARACTERS : 0; // 超出的字數

return (
  <TextInput
    placeholder={isEdit ? '編輯內容' : '有什麼新鮮事?'}
    placeholderTextColor="gray"
    multiline={true}
    numberOfLines={20}
    className="text-white"
    onChangeText={setText}
  >
    <Text className="text-lg">{text.slice(0, MAX_CHARACTERS)}</Text>
    {isOverLimit && (
      <Text className="text-lg bg-amber-900/40">{text.slice(MAX_CHARACTERS)}</Text>
    )}
  </TextInput>
)
guest

0 評論
最舊
最新 最多投票
內聯回饋
查看全部評論