12
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

material-uiでDialog内にTextFieldを置くとフォーカスがおかしくなる問題

Last updated at Posted at 2016-08-14

material-uiでDialog内に配置したTextFieldに日本語とかを入力しようとすると、変換候補表示前にフォーカスが外れてしまう。
「あした」って入力しようとしても「あ」の時点で入力が確定してしまうので「明日」と変換できない問題。

恐らくDialog内に配置した場合のみ発生。普通にTextFieldを使った場合は問題ない。

環境

  • material-ui 0.15.2

問題のある実装

import React, {Component} from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';

export default class Component extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      open: false,
      title: '',
    };
  }

  handleOpen() {
    this.setState({open: true});
  }

  handleClose() {
    this.setState({open: false});
  }

  handleChange(e) {
    this.setState({
      title: e.target.value,
    });
  }

  render() {
    return (
      <div>
        <RaisedButton label="Show Dialog" onTouchTap={this.handleOpen.bind(this)}
        <Dialog
          title="ダイアログ"
          actions={[
            <FlatButton
              label="キャンセル"
              primary={true}
              onTouchTap={this.handleClose.bind(this)}
            />,
            <FlatButton
              label="OK"
              primary={true}
              keyboardFocused={true}
              onTouchTap={this.handleClose.bind(this)}
              disabled={!this.state.title || this.state.title.length < 1}
            />,
          ]}
          modal={false}
          open={this.state.open}
          onRequestClose={this.handleClose.bind(this)}
        >
          <TextField
            value={this.state.title}
            floatingLabelText="タイトル"
            onChange={this.handleChange.bind(this)}
            style={{width: '100%'}}
          />
        </Dialog>
      </div>
    );
  }
}

対処方法

TextFieldのdefaultValueプロパティを使う。

NG)

value={this.state.title}

OK)

defaultValue={this.state.title || null}

defaultValueに空文字を渡すとhintTextとか使ってる場合にヒント(placeholder)が表示されないので空文字ならnullを設定する必要があるので注意。

たぶん Githubのissueはこれ
Closeされてるから最新(現時点では0.15.4)では治ってるかも??

12
7
1

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
12
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?