反应提交事件 - 输入密钥不起作用

时间:2016-09-02 02:56:40

标签: javascript reactjs

我目前正在攻击一个正在使用Soundcloud API的小型前端反应项目。现在非常简单,我只是接受一些用户输入并查询相关歌曲的api端点。由于一些奇怪的原因,我无法获得输入密钥来提交我的表单,因此触发了我的this.handleSubmit()方法。我可以解决它的唯一方法是单击按钮,我的输入功能似乎被打破。我四处搜索,无法找到我忽略的东西,非常感谢任何帮助!

import React from 'react';
import Styles from '../styles/index.js'

class SearchBar extends React.Component {
  constructor(props) {
    super(props);
    this.initPlayer(this.props.song)
  };
  initPlayer(song){
    SC.oEmbed(song, { auto_play: true }).then(function(song) {
      document.getElementById('player').innerHTML = song.html;
    });
  }
  handleSubmit(e){
    e.preventDefault();
    let term = document.getElementById('search').value

    SC.get('/tracks', {
      q: term
    })
      .then( (tracks) => {
        const song = tracks[0].permalink_url;
        if (tracks.length < 1) {
        alert('not found!');
        }
        SC.oEmbed(song, { auto_play: true }).then(function(song) {
          document.getElementById('player').innerHTML = song.html;
        });
        document.getElementById('search').value = '';
      });
    }
  render() {
    return (
      <div>
      <div className="col-lg-12">
        <div style={Styles.playerStyle} id="player"></div>
        <label htmlFor="search">Artist:</label>
        <input type="text" className="form-control" id="search" />
        <div className="text-center">
          <form onSubmit={this.handleSubmit}>
            <button type='submit' style={Styles.buttonStyle} className="btn btn-primary">Submit</button>
          </form>
        </div>
        <div id="player"></div>
        <br />
      </div>
    </div>
    );
  }
}

export default SearchBar;

1 个答案:

答案 0 :(得分:4)

表单只有在焦点时才能通过输入键提交,并且有输入|按钮(类型=&#34;提交&#34;)。所以只需将输入移到表单中即可。

<form onSubmit={this.handleSubmit}>
   <input type="text" className="form-control" id="search" />
   <button type='submit' style={Styles.buttonStyle} className="btn btn-primary">Submit</button>
</form>