React Native:将文本左对齐,但占位符右对齐

问题描述 投票:0回答:1

我正在开发一个 React Native 应用程序,我面临着以不同方式对齐文本输入及其占位符的问题。我希望输入文本向右对齐,同时在同一输入字段中保持占位符向左对齐。我尝试过使用

textAlign
属性,但它会影响输入文本和占位符。这是我尝试过的代码:

import React, { useState } from 'react';
import { View, TextInput, StyleSheet } from 'react-native';

const MyComponent = () => {
  const [text, setText] = useState('');

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.textInput}
        value={text}
        onChangeText={setText}
        placeholder="Placeholder"
        placeholderTextColor="gray"
        textAlign="right" // This affects both input text and placeholder
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderColor: 'gray',
    borderWidth: 1,
    borderRadius: 5,
  },
  textInput: {
    fontSize: 16,
  },
});

export default MyComponent;

如何才能达到输入文本右对齐同时保持占位符文本左对齐的效果?

任何帮助将不胜感激。谢谢!

reactjs react-native placeholder textinput
1个回答
0
投票

我实际上不知道,在 React Native 中是否有任何本地方法可以对占位符进行不同的样式。但由于您更新了状态,一旦输入文本,您就可以对此做出反应并更改对齐方式:

textAlign={text.length > 0 ? "right" : "left"}
© www.soinside.com 2019 - 2024. All rights reserved.