反应中的onKeyPress下的函数调用未被调用

时间:2018-04-12 19:15:16

标签: javascript reactjs semantic-ui-react

在下面的代码中,当我输入搜索字符串并按回车键时,this变得未定义,因此该功能未被调用。任何人都可以帮我理解原因吗?我已经尝试了几乎所有的东西,但似乎没有任何工作,我也找不到任何指向我面临的问题的指针。

    class HomepageBody extends Component{ 
    constructor(props){
    super(props);
    this.state = {
    value :'',
    error: null,
    isLoaded: false,
    array: [],
    mobile: ''
   }
this.readSearchString = this.readSearchString.bind(this);
this.doSomething = this.doSomething.bind(this);
}

 readSearchString(event){
if(event.target.value === ''){
  this.setState({
    error: null,
    array: ''
  });
}
else{
this.setState ({
  value : event.target.value
});
}
}

doSomething = () => {
 fetch(`http://localhost:8080/items?search=${this.state.value}&page=1`, 
 {
  headers: {
    'Accept': 'application/json'
  }
})
  .then(res => res.json())
  .then(
    (result) => {
      if(result.length != 0){
      this.setState({
        isLoaded: true,
        array: result,
        error: null
      });
    }
    else{
      this.setState({
        isLoaded: true,
        error : "No matches found",
        array: ''
      })
    }
    },
    (error) => {
      this.setState({
        isLoaded: true,
        error: "We are experiencing some temporary problem, please try again later"
      });
    }
  )
  }

 render () {
const {mobile} = this.props;
return(
<Container>
  <Header
    as='h1'
    content='Title'
    style={{
      fontSize: mobile ? '1.2em' : '3em',
      fontWeight: 'normal',
      marginBottom: 0,
      marginTop: mobile ? '5em' : '3em',
      display:'block'
    }}
  />
<Input  icon={<Icon name='search' inverted circular link />}
    placeholder='Search .....'
    style={{
    fontSize: mobile ? '1em' : '1em',
    fontWeight: 'normal',
    marginTop: mobile ? '1em' : '1em',
    width: mobile ? '280px' : '600px',
  }}
  onChange={ this.readSearchString }
  onKeyPress={(event) => {
    if(event.key === 'Enter'){
      this.doSomething()
    }
  }}
  focus
/>
  </Container>
)
}
}
   HomepageBody.propTypes = {
   mobile: PropTypes.bool,
}

谢谢, 维克拉姆

2 个答案:

答案 0 :(得分:1)

设置tabIndex="0"的属性,它将起作用。

  

tabindex =“0”允许除链接和表单元素之外的元素   接收键盘焦点。它不会更改Tab键顺序,而是更改   逻辑导航流中的元素,就好像它是一个链接一样   页面。

答案 1 :(得分:0)

是的,那就是我所做的。但它没有用。但是我想出了一个解决方案。如果我没有使用语义ui框架的组件,那么我可以为onKeyPress定义内联函数,它可以正常工作,但是当我使用语义ui框架并使用<Input>时组件,我必须覆盖函数调用。所以我就这样做了

    <Input>
      ..........
      .........
      onKeyPress = {this.onKeyPress}
      </Input>


    onKeyPress= (e) => {
    if(e.key === 'Enter')
    this.doSomething();
   }

所以我认为它与语义ui及其处理组件内事件的方式有关。