我试图用一个非标准的TextInput来制作一个placeholder,因为我需要格式化,而普通的内置TextInput placeholder对我不起作用。
为了让用户能够像普通占位符一样,从行的开头开始写,我在selection={TEXT ? null: {start: 0}的开头设置了光标。当用户进一步键入时,光标返回到开头,并强制用户编写elloH而不是Hello。
我在Snack上做了一个代码示例,运行时问题会更清楚:https://snack.expo.dev/Vv6lNzUCU
怎么解决这个问题呢?
发布于 2022-03-18 14:09:47
我使用了Samuli Hakoniemi's的opacity和zIndex思想,但我想我简化了一些代码:
import React from 'react';
import {
StyleSheet,
View,
TextInput,
Text
} from 'react-native';
export default function App() {
const [TEXT, setText] = React.useState(null);
return (
<View style={{ marginTop: 100, padding: 20 }}>
<View>
<TextInput
style={{
padding: 5,
borderWidth: 1,
zIndex: 1,
}}
autoFocus={true}
onChangeText={(text) => {
setText(text);
}}
value={TEXT}
/>
<View style={{
position: 'absolute',
justifyContent: 'center',
left: 5,
height: '100%',
zIndex: 0,
opacity: (TEXT) ? 0 : 1,
}}>
<Text>
<Text>My </Text>
<Text style={{ backgroundColor: 'yellow' }}>Example</Text>
</Text>
</View>
</View>
</View>
);
}快餐店中的示例:https://snack.expo.dev/mOuNbvxCU
发布于 2022-03-17 23:19:45
我试着学习你的榜样,但无法想出你正在做的所有事情。所以我做了个新点心。它不一定回答你的问题,但这是因为你没有详细说明背后的所有原因。
这是为了在TextInput中没有文本时添加一个自定义占位符。当您添加一些文本时,占位符将消失。
由于您试图显示书面内容的内容,我假设(对不起)您正在尝试构建某种RTE类型的解决方案。因此,我以您的例子为例,添加了这个钩子来突出显示文本内容。因此,尝试highlightedKeywords数组。
下面是要测试的完整解决方案:https://snack.expo.dev/@zvona/manipulation-textinput-selection
如果世博会失去了他们的零食,下面是代码:
import React from 'react';
import { StyleSheet, View, TextInput, Text } from 'react-native';
const highlightedKeywords = ['beep', 'boop'];
const App = () => {
const [inputText, setInputText] = React.useState('');
const highlightContent = () => {
const splitText = inputText.split(' ');
return splitText.map((str) => {
if (highlightedKeywords.includes(str)) {
return <Text style={[styles.overlapText, styles.highlightedText]}>{str}</Text>;
} else {
return <Text style={styles.overlapText}>{str}</Text>;
}
});
};
return (
<View style={styles.container}>
<View style={styles.inputContainer}>
<TextInput style={styles.textInput} onChangeText={setInputText} />
<View style={styles.placeholder}>
{inputText.length ? (
<><Text>{highlightContent()}</Text></>
) : (
<>
<Text>This is my </Text>
<Text style={{ backgroundColor: 'yellow' }}>Placeholder</Text>
</>
)}
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
padding: 20,
},
inputContainer: {
position: 'relative',
width: '100%',
height: 35,
},
textInput: {
zIndex: 2,
borderColor: '#202020',
borderWidth: 2,
height: '100%',
padding: 5,
color: 'transparent',
},
placeholder: {
zIndex: 0,
position: 'absolute',
display: 'block',
height: '100%',
left: 7,
top: 8,
},
overlapText: {
marginRight: '0.25em',
},
highlightedText: {
backgroundColor: '#6699CC',
color: '#ffffff',
},
});
export default App;https://stackoverflow.com/questions/71519912
复制相似问题