入力が空のときにボタンを無効にするにはどうすればいいですか? 質問する

入力が空のときにボタンを無効にするにはどうすればいいですか? 質問する

入力フィールドが空の場合にボタンを無効にしようとしています。これに対する React での最適なアプローチは何ですか?

私は次のようなことをやっています:

<input ref="email"/>

<button disabled={!this.refs.email}>Let me in</button>

これは正しいです?

It's not just duplication of the dynamic attribute, because I'm also curious about transferring/checking the data from one element to another.

ベストアンサー1

You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.

Example using state:

<meta charset="UTF-8">
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<div id="app"></div>
<script type="text/jsx;harmony=true">void function() { "use strict";

var App = React.createClass({
  getInitialState() {
    return {email: ''}
  },
  handleChange(e) {
    this.setState({email: e.target.value})
  },
  render() {
    return <div>
      <input name="email" value={this.state.email} onChange={this.handleChange}/>
      <button type="button" disabled={!this.state.email}>Button</button>
    </div>
  }
})

React.render(<App/>, document.getElementById('app'))

}()</script>

おすすめ記事