【问题标题】:override set style action in TextInput覆盖 TextInput 中的设置样式操作
【发布时间】:2018-12-17 09:26:47
【问题描述】:

我发现 react native 可以扩展父类并覆盖某些功能。我想知道是否有可能或有其他方法。

export default class AppTextInput extends TextInput {

    constructor(props){
       super(props);
    }

    //here is some code I want to do
    style(value){

        var fontSize = value.fontSize;

        //change fontSize
        fontSize = fontSize*2;

        value.fontSize = fontSize;

       //call parent set style function

    }


}

在actionscript 3中,我可以这样做

//do something when visible was set
override public function set visible(value:Boolean):void
{
}

编辑

    hasTriggleFontSizeChange = false;

    realFontSize = 12;

    componentWillMount() {
        var tempStyle = this.props.style;

        if (!this.hasTriggleFontSizeChange) {
            this.hasTriggleFontSizeChange = true;

            var tempFontSize = 6;

            if (tempStyle.hasOwnProperty('fontSize')) {
                tempFontSize = tempStyle['fontSize'];
            }

            tempFontSize = 12;

            var style = {fontSize: tempFontSize};

            let styles = this.props.style;

            //this line can change styles fontSize Value
            styles = {...styles, fontSize: tempFontSize};

            //but this line can't change styles fontSize Value
             this.props.style = styles//{...this.props.style, fontSize: tempFontSize};
        }

    }

【问题讨论】:

    标签: react-native styles textinput


    【解决方案1】:

    你不应该使用继承,而应该使用组合。如果您想要自定义 TextInput,以下是您如何实现该目标的示例:

    import React, { Component } from 'react';
    import { TextInput } from 'react-native';
    
    export default class CustomTextInput extends Component {
      state = {}
    
      render() {
        const { props } = this;
        const style = { fontSize: props.fontSize || 14 }
        return (
          <View style={myStyle}>
            <TextInput
              style={style}
              placeholder={props.placeholder}
              underlineColorAndroid="transparent"
              value={props.value}
              placeholderTextColor={props.placeholderTextColor ? props.placeholderTextColor : colors.lightGray}
            />
          </View >
        );
      }
    
    }
    

    【讨论】:

    • 但是在设置样式时我在哪里可以更改字体大小?我已经编辑了问题。
    • 我遵循了您的代码,无法更改我设置的样式代码中的样式。您能看看编辑部分吗?我想也许我不能直接设置这样的风格。
    猜你喜欢
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多