LoginSignup
0
1

More than 5 years have passed since last update.

React+redux-form+styled-componentsのFieldをblurする

Posted at

inputをblurする

htmlのinputフォームからフォーカスを外したいときは、blur()を呼び出す。

<input id="id" type="text" />
document.getElementById("id").blur();

Reactのinputをblurする

reactでglobal変数のwindow.documentは呼びたくないので、React.createRef()を使う。

class BlurTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();
    this.blurTextInput = this.blurTextInput.bind(this);
  }

  blurTextInput() {
    this.textInput.current.blur();
  }

  render() {
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Blur the text input"
          onClick={this.blurTextInput}
        />
      </div>
    );
  }
}

参考:https://reactjs.org/docs/refs-and-the-dom.html

redux-formのFieldをblurする

withRef を書く。

import { Field } from "redux-form"

class BlurTextInputWithReduxForm extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();
    this.blurTextInput = this.blurTextInput.bind(this);
  }

  blurTextInput() {
    this.textInput.current.blur();
  }

  render() {
    return (
      <div>
        <Field
          type="text"
          ref={this.textInput} 
          withRef
        />
        <input
          type="button"
          value="Blur the text input"
          onClick={this.blurTextInput}
        />
      </div>
    );
  }
}

参考:https://redux-form.com/7.3.0/docs/api/field.md/#-code-withref-boolean-code-optional-

styled-componentsでstyleしたredux-formのFieldをblurする

innerRefで指定するとrefを取得できる。
refからgetRenderedComponent()でDOMを取得して、blurする。

import { Field } from "redux-form"

class BlurTextInputWithReduxFormOfStyledComponents extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();
    this.blurTextInput = this.blurTextInput.bind(this);
  }

  blurTextInput() {
    const inputRefCurrent = this.textInput.current;
    if (inputRefCurrent) {
      inputRefCurrent.getRenderedComponent().blur();
    }

  }

  render() {
    return (
      <div>
        <StyledField
          type="text"
          innerRef={this.textInput} 
          withRef
        />
        <input
          type="button"
          value="Blur the text input"
          onClick={this.blurTextInput}
        />
      </div>
    );
  }
}

const StyledField = styled(Field)`
  border: none;
  flex: 1 0 auto;
  margin: 5px;
  font-size: 17px;
  outline: none;
  height: 30px;
  width: 100%;
`;

参考:https://www.styled-components.com/docs/advanced#refs

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1