Reactjs:当使用Reactjs聚焦表单输入时,如何发出API请求

时间:2019-02-20 16:20:00

标签: reactjs

只要Windows Tab处于焦点位置,下面的代码就会调用axios API。资源 Stackoverflow link

现在正在处理chatText消息的表单输入。我的问题是

当表单输入为焦点时,如何发出API请求。 每当表单输入成为焦点时,我都希望获得回调。

这是表单输入

 <input  type="text" name="chatText" onFocus={this.onFocus} />

这是代码

import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import axios from 'axios';



class Focus extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chatText: ''
    };
this.onfocus = this.onfocus.bind(this);
  }

  componentDidMount() {
window.addEventListener("focus", this.onfocus());
  }

onfocus() {
alert('Am Focused');
 //Make axios call to get data from backend
}


  render() {
    return (
      <span>
        <label>
          <ul>

 <input  type="text" name="chatText" />

          </ul>
        </label>
      </span>
    );
  }
}

2 个答案:

答案 0 :(得分:0)

根据您的代码...

import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import axios from 'axios';

class Focus extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chatText: ''
    };
  }

 onfocus = ()=> {
 alert('Am Focused');
 //Make axios call to get data from backend
 }
  render() {
    return (
      <span>
        <label>
          <ul>
          <input  
            type="text" 
            name="chatText" 
            onFocus={this.onfocus} />
          </ul>
        </label>
      </span>
    );
  }
}

答案 1 :(得分:0)

问题出在您的代码中。当您在-输入错字-

<input type="number" formControlName="imo" class="form-control" min="1" max="5">

<input type="text" name="chatText" onFocus={this.onFocus} />更改为onFocus,它将修复您的代码。