【问题标题】:How can I set an icon within a text input?如何在文本输入中设置图标?
【发布时间】:2019-07-26 07:35:35
【问题描述】:

我正在尝试在文本输入中设置一个图标。 我知道,there is this answer

但由于图标位于TextInput 之外,因此无法按预期工作,我需要它在里面。

这是我目前得到的:

这是我的代码:

         <View style={styles.InputContainer}>
            <Ionicons
              style={styles.IconWithinInput}
              name="ios-search"
              size={24}
            />
            <TextInput
              style={styles.AddEditInputs}
              onChangeText={text => this.setState({ text })}
              value={this.state.text}
            />
          </View>

还有样式:

  AddEditInputs: {
    flex: 1,
    height: 40,
    borderWidth: 1,
  },

  IconWithinInput: {
    padding: 10,
  },

  InputContainer: {
    flexDirection: 'row',
  },

我将输入边框设置为矩形,以便更好地向您展示我的意思。

最后的设计是这样的:

如您所见,输入边框也在图标的底部。

我还需要什么来实现我的需要?

【问题讨论】:

  • 您不能将图标放在文本输入中。您作为答案链接的问题,请查看 11 票赞成的答案。这实际上更好地解释了你应该做什么:stackoverflow.com/a/46468835/1172189

标签: javascript css reactjs react-native ecmascript-6


【解决方案1】:

您不能直接将icon 放在textInput 上。您可以做的是将icontextInputflexDirection 设置为row 的视图一起包装,并将left padding 提供给icon,使其看起来像textInput。如果你想这样做,你可以使用这样的东西

 <View
    style={{
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center'
     }}>
    <View style={{ flexDirection: 'row' }}>
      <View style={{justifyContent: "center", marginRight: 5 }}>
        <Image
          source={{
             uri: 'https://facebook.github.io/react-native/docs/assets/favicon.png',
              }}
              style={{ width: 10, height: 10 }}
            />
          </View>

          <TextInput placeholder="Enter your name" />
        </View>
      </View>

但我的建议是使用react-native-elementsInput component,因为它有leftIcon 作为props。您可以在here找到更多信息

【讨论】:

    【解决方案2】:
    <View style={{flex: 1, flexDirection: 'row'}}>
        <Image
            source={{uri: 'https://facebook.github.io/react-native/docs/assets/favicon.png'}}
            style={{borderWidth: 1,width: 40, height: 40}}
            />
        <TextInput
            onChangeText={(text) => this.setState({text})}
            value={this.state.text}
            style={{borderWidth: 1, height: 40, borderColor: 'grey'}}
            />
             <View>
    
    1. 用 flex 包裹组件并为图标提供宽度。您可以通过一些包装来设置图标,因为它不能包含在文本框中。

    【讨论】:

    • 嗨,尝试添加一些关于您所做更改的评论
    • @user1759586 仅代码的答案被认为是低质量的,edit 您的答案并包含简短说明您的代码解决问题的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多