首页 > 解决方案 > 为 textInput 中输入的文本添加背景颜色反应本机

问题描述

我想添加backgroundColor到本机反应中输入的文本textInput

因此,当用户输入textInput该背景颜色时,输入的文本会增加。

<TextInput
  autoFocus
  value={newTopic}
  textAlignVertical="bottom"
  onChangeText={val => dispatch(setNewTopic(val))}
  style={{
    paddingBottom: 0,
    paddingTop: 2.5,
    paddingRight: 38,
    backgroundColor: "red",
  }}
  blurOnSubmit
  placeholder={Strings.inputs.addTopicPlaceholder}
/>

添加backgroundColor: "red",更改整个输入的背景颜色,但我只需要文本。

我怎样才能在本机反应中做到这一点?

标签: react-native

解决方案


我找不到确切的解决方案。您可以尝试添加相对于 TextInput 的父视图的绝对视图,并根据输入的文本长度修改其宽度。

class Cat extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sampleText: '',
    };
  }
  onChangeText = (sampleText) => {
    this.setState({
      sampleText,
    });
  };
  render() {
    return (
      <View style={{ flex: 1 }}>
        <View style={{ position: 'relative' }}> // to keep the absolute view inside
          <TextInput
            style={{
              backgroundColor: 'rgba(112,232,123,0.2)',
              borderWidth: 1,
            }}
            onChangeText={this.onChangeText}
          />
          <View
            style={{
              position: 'absolute',
              backgroundColor: 'yellow',
              zIndex: -1,
              height: '100%',
              width: this.state.sampleText.length * 7.5, //change based on fontSize
            }}
          />
        </View>
      </View>
    );
  }
}

推荐阅读