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%;
`;