【问题标题】:React form and submit反应表单并提交
【发布时间】:2020-11-11 06:35:26
【问题描述】:

我正在尝试制作一个简单的应用程序,用于与 RIOT API 进行通信。为此,我设置了一个带有表单和提交按钮的 SearchBar 组件。我想要实现的只是在提交后从表单中获取名称,将其保存到 this.state.name 并将其传递给执行获取的组件。我只是无法掌握事件处理程序...

  class SearchBar extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            name: ""
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this)
    }
    
    handleChange(e){
        e.preventDefault()
    }
    handleSubmit(e) {
        this.setState({
            name: e.target.value
        });
    };

    render() {
        return (
<Form>
        <Form.Group controlId="formBasicEmail">
            <Form.Control type="input" placeholder="Enter your summoner name" onChange={this.handleChange}/>
        </Form.Group>

        <Button variant="primary" type="submit" onClick={this.handleSubmit}>
                Let's go!
        </Button>
        <p>{this.state.name}</p>
</Form>
        )
    }
}

提前感谢您的帮助!

【问题讨论】:

    标签: reactjs forms submit setstate


    【解决方案1】:

    尝试更新表单以在 Form 而不是按钮上使用 onSubmit 处理程序。鉴于按钮的类型为submit,单击按钮将触发表单提交事件,而按钮上没有处理程序。还将preventDefault() 移动到onSubmit 而不是onChange 以避免页面在提交事件时刷新:

    class SearchBar extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          name: ""
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this)
      }
    
      handleChange(e) {
        this.setState({
          name: e.target.value
        });
    
      }
      handleSubmit(e) {
        e.preventDefault();
        // send data to API
      };
    
      render() {
        return (
          <Form onSubmit={this.handleSubmit}>
            <Form.Group controlId="formBasicEmail">
              <Form.Control type="input" placeholder="Enter your summoner name" onChange={this.handleChange} />
            </Form.Group>
    
            <Button variant="primary" type="submit">
              Let's go!
            </Button>
            <p>{this.state.name}</p>
          </Form>
        )
      }
    }
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2022-07-05
      • 2018-11-28
      • 1970-01-01
      • 2019-07-07
      • 2016-04-14
      • 2012-05-07
      • 2012-08-09
      • 2020-08-22
      • 2021-06-19
      相关资源
      最近更新 更多