ReactJS获取Enter键以执行与单击按钮相同的操作

时间:2019-06-08 17:38:13

标签: javascript reactjs

我在响应中创建了这个网站(https://animeimages.netlify.com/)。您基本上将系列名称放在搜索栏中,单击按钮,它会返回图像。但是,当您单击Enter时,页面将重新启动。是否可以按Enter并使它执行与单击搜索按钮相同的操作。表单和按钮是不同的组件。

app.js

import React, { Component } from 'react';
import './App.css';
import { FormGroup, FormControl, InputGroup, Form, } from 'react-bootstrap'
import Conditional from './conditional'
import Button2 from './button.js'


class App extends Component{
    constructor(props){
        super(props)
        this.state = {
            isLoading: true,
            isLoading2: true,
            query: '',
            fimg: [],
        }
        this.isloaded = this.isLoaded.bind(this)

    }
    isLoaded  = () => {
        this.setState({
            isLoading: !this.state.isLoading,
            isLoading2: false
        })

    }

    fimgSet = fimgData => {
        this.setState({
            fimg: fimgData
        });
    }


    render(){
        return(
        <div className="App">
            <div className="App-title"> <span className="bg-title"> Anime Image Gallery </span></div>
            <div className="app-mini-title"> <span className="bg-title">Enter the name of an Anime series</span></div>
            <Form className="OutterformSize">
            <FormGroup>
                {/* <Form.Label> <span className=".bg-title">Enter the name of an Anime series </span></Form.Label> */}

                <InputGroup className="formSize">
                    <FormControl
                        size="lg"
                        type="text"
                        placeholder="Try Searching Pokémon, DRAGON+BALL or Wallpaper"
                        value = {this.state.query}
                        onChange= {event => {this.setState({query: event.target.value})}}


                        />
                </InputGroup>
            </FormGroup>
            <Button2  query={this.state.query} isLoading={this.state.isLoading} isLoaded={this.isLoaded} callbackFromParent={this.fimgSet}/>
            </Form>
            <div>
                <Conditional images={this.state.fimg} isLoading2={this.state.isLoading2}/>
            </div>
        </div>
        )
    }
}

export default App;

button.js

import React from "react";
import Spinner from 'react-bootstrap/Spinner';
import { ButtonToolbar } from "react-bootstrap";
import  Button from 'react-bootstrap/Button'


class Button2 extends React.Component{
    constructor(props){
        super(props)
        this.OnSearch = this.OnSearch.bind(this)
    }

    OnSearch(){
        this.props.isLoaded();
        // console.log("Seatch Clicked");
        // console.log(this.props.query)
        const $ = require('cheerio');
        const BASE_URL = 'https://cors-anywhere.herokuapp.com/https://www.zerochan.net/'
        const DYM_URL = `${BASE_URL}${this.props.query}?s=fav` //'Re%3AZero+Kara+Hajimeru+Isekai+Seikatsu' 
        // console.log(DYM_URL)
        // console.log(DYM_URL)
        //const URL = 'https://cors-anywhere.herokuapp.com/https://www.zerochan.net/Re%3AZero+Kara+Hajimeru+Isekai+Seikatsu?screen=1&s=fav'
        // const request= require("request-promise") 
    // const $ = require('cheerio')
        // const url ="https://www.zerochan.net/n?s=fav"
        let headers = new Headers({
            'Accept' : "text/plain",
            'Content-Type': "text/plain",
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Mobile Safari/537.36'
        });
        fetch(DYM_URL, {
            method: "GET",
            mode: "cors",
            cache: "no-cache",
            credentials: 'same-origin',
            header: headers,
            //lss
        })
            .then(res => res.text())
            .then(body => {
                // console.log(body)
                const imgUrls = [];
                const imgLen = $('p > a', body).length;
                for (let i = 0; i < imgLen; i++){
                    imgUrls[i]=($('p > a', body)[i].attribs.href);
                }
                const regex = /https:\/\/static.zerochan.net.+.(jpg|png)/
                const match = imgUrls.filter(value =>  regex.test(value));
                // console.log("match: ", match);

                this.props.callbackFromParent(match);
                this.props.isLoaded();

                // this.setState({
                //     fimg: match
                // })

            })
            .catch(function(err){
                console.log(err);

            });
        }

        render(){
            if (this.props.isLoading === false){
                return(
                <div>
                    <ButtonToolbar className="text-center d-block">
                    <Button variant="primary">
                        <Spinner
                        as="span"
                        animation="border"
                        size="sm"
                        role="status"
                        aria-hidden="true"
                        />
                        Loading
                    </Button>
                    </ButtonToolbar>
                </div>
                /* <div>
                    {}
                </div> */

            )} else {
            return(
                <div>
                    <ButtonToolbar className="text-center d-block">
                        <Button variant="primary" type="button"  onClick={() => this.OnSearch()}>Search</Button>
                    </ButtonToolbar>
                </div>

                // <div>
                // <button type="button"  onClick={() => this.OnSearch()}>search</button>
                // </div>
                )}

        }
}


export default Button2;


github回购: https://github.com/Kohdz/ImageScraper

1 个答案:

答案 0 :(得分:0)

您应将事件处理程序移至<form> onSubmit并从onClick中删除<button>事件,这将导致在您选择以下任一条件时触发表单提交按键盘上的Enter或单击按钮。

相关问题