首页 > 解决方案 > 我想为 React-Native TextInput 的每个字符值使用不同的颜色和字体系列

问题描述

我的代码:

export default class ClearComponent extends Component {


    color= ['red', 'blue']
    font_family= ['normal', 'notoserif', 'sans-serif']
    state = {
    text: '',
    context: [
      
    ],
    color:"black",
    font_family:"normal",
  };

  textInputOnChange = (text) => {
    const {context, color, font_family} = this.state;
    
    if (context.length > text.length) {
        
        context.pop()
       this.setState({
            context


       })
      
    } else {
        this.setState({
            context:[...context,{
                value: text[text.length - 1],
                color,
                font_family
              }]
        })
      
      
    }
  };
 

  render() {
    const {context} = this.state;
    const { color, font_family} =  this
    return (
      
      <View>
        <TextInput  onChangeText={this.textInputOnChange}>
          {context.map((element) => {
              
            return (
              <Text
                style={{fontFamily: element.font_family, color: element.color,fontSize:25}}>
                {element.value}
              </Text>
            );
          })}
        </TextInput>
        <Picker
        selectedValue={this.state.font_family}
        mode="dropdown"
        onValueChange={(itemValue, itemIndex) => {
            this.setState({font_family: itemValue});
          }}
        >
          {font_family.map((element) => {
            return (
              <Picker.Item
                key={(key) => key.id}
                value={element}
                label={element}
              />
            );
          })}
        </Picker>
        <View style={{flexDirection: 'row'}}>
          {color.map((element) => {
            return (
              <TouchableOpacity onPress={()=>{
                  this.setState({color:element}) 
                  console.log(this)}}>
                <Text
                  style={{
                    height: 25,
                    width: 25,
                    
                    backgroundColor: element,
                    borderRadius: 20,
                    marginHorizontal: 2,
                    marginVertical: 2,
                  }}/>
              </TouchableOpacity>
            );
          })}
        </View>
        <Text style={{fontFamily:"",fontSize:40}}>dsadas</Text>
      </View>
    );
  }
}

我正在开发一个笔记本应用程序。我也遇到过这样的问题,我找到了一些解决方案,但还不够,它带来了很多问题。

我想为每个字符制作不同的样式定义,但这段代码效果不佳。

有专门的图书馆吗?

我对您的替代解决方案持开放态度。

标签: react-nativereact-native-androidreact-native-textinput

解决方案


推荐阅读