React从表单获取输入

问题描述

我正在构建一个简单的react应用程序,用户可以在其中输入数字显示在屏幕上。

print (df.to_string())
                                          event_title                            name                                    address         city       state zipCode             location                                            webSite                                                fee                              event_dates                                      opening_dates                                        description
0   The San Diego Museum of Art Welcomes a Special...         San Diego Museum of Art                 1450 El Prado,Balboa Park    San Diego          CA   92101    Central San Diego                            https://www.sdmart.org/                                                NaN    Starts On 6-18-2020 Ends On 1-10-2021  Opens virtually on June 18. The work will beco...  The San Diego Museum of Art is launching its f...
1                New Exhibit: Miller Dairy Remembered  Lemon grove Historical Society  3185 Olive Street,Treganza Heritage Park  Lemon grove          CA   91945    Central San Diego                        http://www.lghistorical.org  Children 12 and under free and must be accompa...    Starts On 6-27-2020 Ends On 12-4-2020  Exhibit on view Saturdays 11 am to 2 pm; close...  From 1926 there were cows smack in the midst o...
2                               Gizmos and Shivelight             distinction gallery                           317 E. Grand Ave    Escondido          CA   92025  north County Inland                      http://www.distinctionart.com                                                NaN     Starts On 7-14-2020 Ends On 9-5-2020                                08/08/20 - 09/05/20  distinction gallery is proud to present our so...
3                  Virtual opening - July Exhibitions               Vision Art Museum                   2825 Dewey Rd. Suite 100    San Diego          CA   92106    Central San Diego                    http://www.visionsartmuseum.org                                               Free    Starts On 7-18-2020 Ends On 10-4-2020                                                NaN  Join Visions Art Museum for a virtual exhibiti...
4   Laying it Bare: The Art of Walter Redondo and ...             Fresh Paint gallery                     1020-B Prospect Street     La Jolla          CA   92037    Central San Diego                      http://freshpaintgallery.com/                                                NaN     Starts On 8-1-2020 Ends On 9-27-2020            Tuesday through Sunday. Mondays closed.  A two-person exhibit of new abstract expressio...
5    Online oil painting lessons with Concetta Antico                             NaN                                        NaN          NaN         NaN     NaN              Virtual  http://concettaantico.com/live-online-oil-pain...                                                NaN    Starts On 8-10-2020 Ends On 8-31-2020                                                NaN  Anyone can learn to paint like the masters! Ov...
6             MOMENTUM: A Creative Industry Symposium                Vanguard Culture                                   Via Zoom    San Diego  California   92101              Virtual  https://www.eventbrite.com/e/momentum-a-creati...                             $10 suggested donation     Starts On 8-17-2020 Ends On 9-7-2020                                                NaN  MOMENTUM: A Creative Industry Symposium Monday...
7                    Virtual Locals Invitational Show        Art & Frames of Coronado                             936 ORANGE AVE     Coronado          CA   92118                    0  https://www.artsteps.com/view/5eed0ad62cd0d65b...                                               free     Starts On 8-21-2020 Ends On 8-1-2021                                                NaN  Art and Frames of Coronado invites you to our ...
8                                          HERE & Now          R.B. Stevenson gallery              7661 Girard Avenue,Suite 101     La Jolla  California   92037    Central San Diego                  http://www.rbstevensongallery.com                                               Free    Starts On 8-22-2020 Ends On 9-25-2020                           Tuesday through Saturday  R.B.Stevenson gallery is pleased to announce t...
9                     Art Unites Learning: normal 2.0                      Art Unites                                        NaN    San Diego         NaN   92116    Central San Diego    https://www.facebook.com/events/956878098104971                                               Free    Starts On 8-25-2020 Ends On 8-25-2020                                                NaN  Please join us on Tuesday,August 25th as we: ...
10  Image Quest Sojourn; Visual Journaling for Per...        Pamela Underwood Studios                                    Virtual          NaN         NaN     NaN              Virtual  http://www.pamelaunderwood.com/event/new-onlin...                                            $595.00   Starts On 8-26-2020 Ends On 11-11-2020                                                NaN  Create a personal Image Quest resource journal...
11  Behind The Exhibition: Southern California Con...         Oceanside Museum of Art                          704 Pier View Way    Oceanside  California   92054              Virtual  https://oma-online.org/events/behind-the-exhib...            No fee required. Donations recommended.    Starts On 8-27-2020 Ends On 8-27-2020                                                NaN  Join curator Beth Smith and exhibitions manage...
12          Lay it on Thick,a Virtual Art Exhibition    San Diego Watercolor Society                    2825 Dewey Rd Bldg #202    San Diego  California   92106                    0                               https://www.sdws.org                                                NaN    Starts On 8-30-2020 Ends On 9-26-2020                                                NaN  The San Diego Watercolor Society proudly prese...
13      The Forum: Marketing & branding for Creatives                Vanguard Culture                                   Via Zoom    San Diego          CA   92101      South San Diego                        http://vanguardculture.com/                              $5 suggested donation      Starts On 9-1-2020 Ends On 9-1-2020                                                NaN  Attention creative industry professionals! Joi...
14                       Write or Die Solo Exhibition                 You Belong Here                         3619 EL CAJON BLVD    San Diego          CA   92104    Central San Diego  http://www.youbelongsd.com/upcoming-events/wri...            $10 donation to benefit You Belong Here      Starts On 9-4-2020 Ends On 9-6-2020                                                NaN  Write or Die is an immersive installation and ...
15     SDVAN presents Art San Diego at Bread and Salt   San Diego Visual Arts Network                         1955 Julian Avenue     San Digo          CA   92113    Central San Diego  http://www.sdvisualarts.net and https://www.br...                                               Free    Starts On 9-5-2020 Ends On 10-24-2020                                                NaN  We are pleased to announce the four artist rec...
16               The Coming of Treganza Heritage Park  Lemon grove Historical Society                          3185 Olive Street  Lemon grove          CA   91945    Central San Diego                        http://www.lghistorical.org                                  Free for all ages    Starts On 9-10-2020 Ends On 9-10-2020  The park is open daily,8 am to 8 pm. Covid 19...  Lemon grove\'s central city park will be renam...
17               Online oil painting course | 4 weeks                             NaN                                        NaN          NaN         NaN     NaN              Virtual  http://concettaantico.com/live-online-oil-pain...                                                NaN    Starts On 9-14-2020 Ends On 10-5-2020                                                NaN  Over 4 weekly Zoom lessons,learn the techniqu...
18               Online oil painting course | 4 weeks                             NaN                                        NaN          NaN         NaN     NaN              Virtual  http://concettaantico.com/live-online-oil-pain...                                                NaN   Starts On 10-12-2020 Ends On 11-2-2020                                                NaN  Over 4 weekly Zoom lessons,learn the techniqu...
19                    36th Annual Mission Fed ArtWalk             Mission Fed ArtWalk                                 Ash Street    San Diego  California   92101    Central San Diego                          www.missionfedartwalk.org                                               Free    Starts On 11-7-2020 Ends On 11-8-2020                            Sat and Sun Nov 7 and 8  Mission Fed ArtWalk returns to San Diego’s Lit...
20             Mingei Pop Up Workshop: My Daruma Doll            New Childrens Museum                     200 West Island Avenue    San Diego  California   92101    Central San Diego                        http://thinkplaycreate.org/                                Free with admission  Starts On 11-13-2020 Ends On 11-13-2020                                                NaN  Join Mingei International Museum at The New Ch...
class Main extends React.Component {
    state = {
        list: [1,2,3,4,5]
    }
    newElementHandler = (e) => {
        let newlist = this.state.list
        newlist.push(e.target.value)
        this.setState({
            list: newlist
        })
    }
    submitHandler = (e) => {
        e.preventDefault()
    }
    render() {
        let showlist = this.state.list
        return (
            <div>
                <div>
                {showlist.map(ele=>(
                    <div>{ele}</div>
                ))}
                </div>
                <form onSubmit={this.submitHandler}>
                    <input onChange={this.newElementHandler} />
                    <button type="submit" >Submit</button>
                </form>
                
            </div>
        )
    }
}

ReactDOM.render(<Main />,document.querySelector('.react'));

但是,我只希望在单击“提交”时显示该号码。现在,我一开始输入,它就会显示数字。有人可以帮忙修改代码,以便它仅更新表单提交时的状态,从而显示编号。谢谢

解决方法

删除更改处理程序,因为您只想在提交表单时才显示更改。使用ref获取对提交处理程序中的input元素的引用,获取值,然后调用export TSC_NONPOLLING_WATCHER="1"

setState
class Main extends React.Component {
    state = {
        list: [1,2,3,4,5]
    }
    inputRef = React.createRef();
    submitHandler = (e) => {
        e.preventDefault()
        this.setState({
          list: [
            ...this.state.list,this.inputRef.current.value
          ]
        });
    }
    render() {
        let showlist = this.state.list
        return (
            <div>
                <div>
                    {showlist.map(ele => (
                        <div>{ele}</div>
                    ))}
                </div>
                <form onSubmit={this.submitHandler}>
                    <input ref={this.inputRef} />
                    <button type="submit" >Submit</button>
                </form>

            </div>
        )
    }
}

ReactDOM.render(<Main />,document.querySelector('.react'));

请注意,由于您使用的是React,因此您不应像在上面那样在更新时更改状态-克隆/传播状态。 (避免使用<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div class='react'></div>

,

在回答之前,请注意以下几点:

    let newlist = this.state.list
    newlist.push(e.target.value)

否! 您永远不要直接改变状态,而只需修改状态副本:

    const newlist = [...this.state.list];
    newlist.push(e.target.value);

或者:

const newlist = [...this.state.list,e.target.value];

对于答案本身,您可以选择以下任一种:

a。使用另一个保存当前值的状态片:

import React,{ Component } from 'react';
import { render } from 'react-dom';
import Employee from './Employee';
import {EmployeeProvider} from './context';
import './style.css';

class Main extends Component {
    state = {
        list: [1,5],currentValue: '',}
    newElementHandler = (e) => {
      this.setState({
        currentValue: e.target.value
      })
    }
    submitHandler = (e) => {
        e.preventDefault();
        this.setState({
          list: [...this.state.list,this.state.currentValue],currentValue: ''
        });
    }
    
    render() {
        let showlist = this.state.list
        return (
            <div>
                <div>
                {showlist.map(ele=>(
                    <div>{ele}</div>
                ))}
                </div>
                <form onSubmit={this.submitHandler}>
                    <input value={this.state.currentValue} onChange={this.newElementHandler} />
                    <button type="submit" >Submit</button>
                </form>
                
            </div>
        )
    }
}
render(<Main />,document.getElementById('root'));

b。使用表单数据:

import React,{ Component } from 'react';
import { render } from 'react-dom';
import Employee from './Employee';
import {EmployeeProvider} from './context';
import './style.css';

class Main extends Component {

    state = {
        list: [1,}
    submitHandler = (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        this.setState({
          list: [...this.state.list,formData.get('value')]
        })
    }
    
    render() {
        let showlist = this.state.list
        return (
            <div>
                <div>
                {showlist.map(ele=>(
                    <div>{ele}</div>
                ))}
                </div>
                <form onSubmit={this.submitHandler}>
                    <input name='value' />
                    <button type="submit" >Submit</button>
                </form>
                
            </div>
        )
    }
}
render(<Main />,document.getElementById('root'));

c。使用裁判(@CertainPerformance的答案)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...