React-Native自定义TextInput如何内置placeholderTextColor与cursorColor
如何将placeholderTextColor和cursorColor内置到React Native自定义TextInput组件中
你只需要在自定义TextInput组件内部为这两个属性设置默认值,同时保留外部传入值的优先级即可。修改后的组件代码如下:
import { TextInput as OldTextInput } from "react-native"; function TextInput({ style, placeholderTextColor = "#ffffffac", cursorColor = "#ffffffac", ...otherProps }) { const defaultStyle = { fontFamily: "poppins", borderWidth: 1, borderColor: "#ffffffac", borderRadius: 10, backgroundColor: "#194F4D", paddingVertical: 8, paddingHorizontal: 15, width: "100%", color: "white", }; const mergedStyle = { ...defaultStyle, ...style }; return ( <OldTextInput style={mergedStyle} placeholderTextColor={placeholderTextColor} cursorColor={cursorColor} {...otherProps} /> ); } export default TextInput;
逻辑说明
- 在组件参数解构时,直接为
placeholderTextColor和cursorColor设置默认值#ffffffac - 若使用组件时传入这两个属性,外部值会自动覆盖默认值,保留组件灵活性
- 最后将处理后的属性与剩余
otherProps一起透传给原生OldTextInput
使用示例
现在可以简化使用代码,无需重复传入这两个属性:
<TextInput placeholder="placeholder" onFocus={() => handleInputFocus()} onBlur={handleBlur} value={reminderName} onChangeText={(text) => setReminderName(text)} ></TextInput>
如果需要临时修改某个输入框的属性,直接传入即可覆盖默认值:
<TextInput placeholder="自定义占位符颜色" placeholderTextColor="#cccccc" cursorColor="#cccccc" // 其他属性... ></TextInput>
内容的提问来源于stack exchange,提问作者mertavcioglu
相关产品推荐
相关产品推荐

