簡體   English   中英

如何在 ReactNative 中將貨幣圖標放在 TextInput 的值前面?

[英]How can I put currency icon in front of the value of TextInput in ReactNative?

當用戶輸入金額時,我需要將貨幣圖標放在值前面,但這並不容易。 我花了一整天,但仍然沒有找到理想的解決方案。 我最好的方法是將子組件包裝到 TextInput,如下所示:

          <TextInput
            style={SS.input}
            placeholder={props.placeholder}
            underlineColorAndroid='transparent' editable={!props.disabled}
            keyboardType={keyboardType} autoCapitalize='none'
            autoCorrect={false} selection={state.position}
            value={state.value} onChangeText={this._onChangeText}
            onFocus={this._onFocus} onBlur={this._onBlur}
            autoFocus={autoFocus}>
            {!!this.props.icon && !!state.value && (
              <Text style={{marginLeft: 10}}>{this.props.icon}</Text>
            )}
          </TextInput>

但這個決定有一些缺點。 第一個無法為子組件設置樣式,我無法從數量設置左填充。 第二個是 TextInput 的焦點在圖標之后。 有人可以幫我嗎。 在此處輸入圖片說明

我找到了最好的解決方案,您需要這樣做,將 TextInput 的樣式設置為不可見。 並且為了顯示輸入,在頂部添加具有相同參數的 Text 組件,使其正好顯示在原生組件的頂部。 它就像一個面具。

<View style={container}>
 <TextInput
            style={[SS.input, styles.input]}
            placeholder={props.placeholder}
            value={state.value} onChangeText={this._onChangeText}
            onFocus={this._onFocus} onBlur={this._onBlur}
            // make invisible text
            color={'rgba(0,0,0,0)'} 
            autoFocus={autoFocus} />
          // render currency symbol with value that depends on the props
          {!!props.maskedTextColor !! && props.currencySymbol && !!state.value && (
            <Text
              color={props.maskedTextColor}
              textStyle={'menuSliders'}
              style={styles.maskedText}>
              {`${state.value} ${props.currencySymbol}`}
            </Text>
          )}
<View/>

並且您需要將 Text 組件與組件完全相同,並放置樣式,在我的情況下是:

    maskedText: {
      position: 'absolute',
      left: 15,
    },

我相信您正在尋找的是 CSS ::after偽元素。 這是一個使用contenteditable跨度的示例:

 #money { border: 1px solid black; padding: 2px 4px; } #money::after { content: " €"; }
 <span id="money" contenteditable="true"></span>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM