该类不适用于输入元素reactjs

时间:2018-09-12 09:42:52

标签: reactjs

当前,要在输入元素不为空并且用户输入文本时设置输入元素的样式。下面是代码片段。当!input_active但将条件设置为(!input_active &&!inputEmpty)时,将应用该类。

constructor(props) {
  super(props);
  this.input_text_ref = React.createRef();
  this.state = {
    input_active: true,
  };
}

focus = () => {
  console.log("focus");
  this.setState({
    input_active: true
  });
};

blur = () => {
  console.log("blur");
  this.setState({
    input_active: false
  });
};
handle_text_input_change = (event) => {
  this.props.onChange(event);
  this.setState({
    text_input_value: event.target.value
  });
  console.log("withinhandle", this.state.text_input_value);
};
render() {

    const {
      value,
      disabled,
      ...rest
    } = this.props;
    const {
      input_active
    } = this.state;
    console.log(input_active);
    let input_element_classes = [''];
    let inputEmpty = value.length == 0;
    console.log("inputempty", inputEmpty);

    const inputCompiled = value.length > 0;

    if (input_active && !inputEmpty) {
      input_element_classes.push('blur');
    }

    return (
      <input {...rest}
          className={input_element_classes.join(' ')}
          type="text"
          ref={this.input_text_ref}
          onChange={this.handle_text_input_change}
          disabled={disabled}
          onBlur={this.blur}
          //onKeyDown={this.shouldBlur}
          onFocus={this.focus}
      />
    );
  }

有人可以帮我吗?另外,基于输入元素验证(空,禁用,用户输入文本等),如何更改输入元素的样式。从代码中可以理解,我基于验证使用了一组类(input_element_classes),我弹出该类并推送其他一些类。还有其他简单的方法可以做到这一点。谢谢。

1 个答案:

答案 0 :(得分:0)

看起来有点过载。如果我答对了,您可以这样写:

export class TextInput extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isActive: props.value.length > 0
    };
  }

  static defaultProps = {
    value: "",
    disabled: false
  };

  onFocus = () => {
    this.setState({ isActive: true });
  };

  onBlur = ({ target }) => {
    this.setState({ isActive: target.value.length > 0 });
  };

  render() {
    const { disabled, ...rest } = this.props;
    const { isActive } = this.state;
    return (
      <input
        {...rest}
        className={`text-input ${isActive ? "active" : ""}`}
        type="text"
        disabled={disabled}
        onBlur={this.onBlur}
        onFocus={this.onFocus}
      />
    );
  }
}

您可以在沙箱https://codesandbox.io/s/zl9mmvmp33

中找到示例