React Native-自定义组件样式更改时文本消失

时间:2018-10-22 18:03:46

标签: react-native textinput

在尝试将条件样式应用于自定义组件时遇到奇怪的错误。每当样式更改出现时,文本就会完全消失。如果我再次开始键入,将显示新样式,但是一旦样式再次更改,文本将再次消失。如果我将样式应用为静态样式,则自定义样式完全可以正常工作。我不确定是什么问题。预先感谢您的帮助。

        <UserInput
          style = {!this.state.isValidEmail ? styles.errorInline : styles.default}
          placeholder="Email"
          autoCapitalize={'none'}
          returnKeyType={'next'}
          autoCorrect={false}
          onSubmitEditing={() => this.focusNextField('password')}
          updateState={(email) => {
            let formattedEmail = email.trim();
            this.state.initialValidationChecked? this.validate(formattedEmail) : this.setState({formattedEmail})}
          } 
          blurOnSubmit={true}
          onBlur2={(event) => this.validate(event.nativeEvent.text.trim())}
        />

errorInline: {
    color: 'red',
},
default : {
    color: '#777777'
}

export default class UserInput extends Component {

  componentDidMount() {
    if (this.props.onRef != null) {
        this.props.onRef(this)
    }
  }

  onSubmitEditing() {
      if(this.props.onSubmitEditing){
          this.props.onSubmitEditing();
      }
  }

  focus() {
    this.textInput.focus();
  }

  render() {
    return (
      <View style={styles.inputWrapper}>
        <TextInput
          style={[styles.input, this.props.style]}
          placeholder={this.props.placeholder}
          secureTextEntry={this.props.secureTextEntry}
          autoCorrect={this.props.autoCorrect}
          autoCapitalize={this.props.autoCapitalize}
          returnKeyType={this.props.returnKeyType}
          onChangeText={(value) => this.props.updateState(value)}
          onEndEditing={(value) => {  if(this.props.onBlur2) return this.props.onBlur2(value)}}
          ref={input => this.textInput = input}
          blurOnSubmit={this.props.blurOnSubmit}
          onSubmitEditing={this.onSubmitEditing.bind(this)}
          underlineColorAndroid='transparent'
        />
      </View>
    );
  }

}

UserInput.propTypes = {
  placeholder: PropTypes.string.isRequired,
  secureTextEntry: PropTypes.bool,
  autoCorrect: PropTypes.bool,
  autoCapitalize: PropTypes.string,
  returnKeyType: PropTypes.string,
};

const DEVICE_WIDTH = Dimensions.get('window').width;

const styles = StyleSheet.create({
  input: {
    width: DEVICE_WIDTH - 70,
    height: 40,
    marginHorizontal: 20,
    marginBottom: 30,
    color: '#777777',
    borderBottomWidth: 1, 
    borderBottomColor: '#0099cc'
  },
  inputWrapper: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1,
  },
});

1 个答案:

答案 0 :(得分:0)

样式作为对象(键值对)给出。 但是请在下面的行中查看您的代码

style = {!this.state.isValidEmail ? styles.errorInline : 'none'}

this.state.isValidEmail返回true时,您只是在给样式“ none”,这是语法错误,您应该返回类似这样的内容

style = {!this.state.isValidEmail ? styles.errorInline : {display: 'none'}}