通过单击来自不同组件的按钮提交

时间:2019-12-17 10:17:17

标签: html reactjs

我想在用户单击按钮时提交表单结果,但是该按钮未嵌入表单本身。我想将按钮放在应用程序组件中,因此我在这里遵循了最高评分的建议:

How to submit form from a button outside that component in React?

但是它不起作用。这是我的代码:

textbox.jsx

import React, { Component } from "react";

class TextBox extends React.Component {
  render() {
    return (
      <form id="my-form" onSubmit={this.mySubmitHandler} className="textarea">
        <textarea
          className="textarea"
          placeholder={"Enter text in " + this.props.language}
          value={this.props.input}
          type="text"
          name="equation"
          onChange={this.handleInputChange}
          onKeyDown={this.keyPress}
        />
      </form>
    );
  }
  handleInputChange = event => {
    event.preventDefault();
    this.setState({
      [event.target.name]: event.target.value
    });
    this.props.inputChange(event.target.value);
  };

  mySubmitHandler = event => {
    console.log("SUBMIT");
    event.preventDefault();
    this.props.formSubmitted();
  };

  keyPress = event => {
    if (event.keyCode == 13 && event.shiftKey == false) {
      this.mySubmitHandler(event);
    }
  };
}

export default TextBox;

app.js

class App extends React.Component {
  render() {
    return (
      <button id="my-form" className="Submit" type="submit"></button>
      <div className="textContainer">
        <div className="LeftText">
          <TextBox
            autotranslate={this.state.auto_translate}
            formSubmitted={this.formSubmitted}
            inputChange={this.inputChange}
            input={this.state.input}
            language={this.state.languages[this.state.source_i]}
          />
        </div>
     );
  }
}

1 个答案:

答案 0 :(得分:2)

尝试将form attribute添加到您的button

<button form="my-form" id="my-form" type="submit">
  Submit
</button>
import React from 'react';
import ReactDOM from 'react-dom';

class TextBox extends React.Component {
  render() {
    return (
      <form id="my-form" onSubmit={this.mySubmitHandler}>
        <textarea />
      </form>
    );
  }

  mySubmitHandler = event => {
    console.log('SUBMIT');
    event.preventDefault();
  };
}

class App extends React.Component {
  render() {
    return (
      <>
        <TextBox />
        <button form="my-form" type="submit">
          Submit
        </button>
      </>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

Edit reverent-bush-8elfn