【问题标题】:React JS: How to pass a value to other Component onSubmitReact JS:如何将值传递给其他组件 onSubmit
【发布时间】:2020-12-30 18:20:38
【问题描述】:

我尝试创建一个按钮,点击后会弹出一个窗口。弹出窗口包含一个表单,可以让我输入任何新条目。提交时,应将条目传递给主组件。

我有两个组件。主要组件是“App”组件,另一个组件是“Popup”组件。

这是我的代码:

App.js

import React, { Component } from "react";
import Popup from "./Popup.js";
import "./styles.css";

class App extends Component {
  showPopup = false;

  createEntry = () => {
    this.showPopup = true;
    this.setState({ showPopup: this.showPopup });
  };

  handleSubmit = (value) => {
    console.log("New Entry: " + value);
    this.showPopup = false;
    this.setState({ showPopup: this.showPopup });
  };

  render() {
    return (
      <React.Fragment>
        <button onClick={this.createEntry}> + </button>
        {this.showPopup ? <Popup handleSubmit={this.handleSubmit} /> : null}
      </React.Fragment>
    );
  }
}

export default App;

Popup.js

import React, { Component } from "react";
import "./styles.css";

class Popup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    };

    // I want to pass the submitted value to the App Component
    this.handleSubmit = this.props.handleSubmit.bind(this, this.state.value);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange = (event) => {
    this.setState({ value: event.target.value });
  };

  render() {
    return (
      <React.Fragment>
        <div className="popup">
          <div className="popup_inner">
            <div> Create New Entry </div>
            <form onSubmit={this.handleSubmit}>
              <label>
                <input
                  type="text"
                  name="name"
                  value={this.state.value}
                  onChange={this.handleChange}
                />
              </label>
              <input type="submit" value="Submit" />
            </form>
          </div>
        </div>
      </React.Fragment>
    );
  }
}

export default Popup;

styles.css

.App {
  font-family: sans-serif;
  text-align: center;
}
.popup {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  background-color: rgba(0, 0, 0, 0.5);
}
.popup_inner {
  position: absolute;
  left: 25%;
  right: 25%;
  top: 25%;
  bottom: 25%;
  margin: auto;
  background: white;
}

我尝试通过使用 handleSubmit 作为 prop 方法将“值”传递给“handleSubmit”方法,但这不起作用。

将值传递给 App 组件的合适方法是什么?

我还是 React 的新手,所以请多多包涵。

提前致谢。

【问题讨论】:

标签: reactjs components parameter-passing onsubmit


【解决方案1】:

答案就在您的问题中。您将它作为道具方法传递,因此您必须从道具访问它。 在您的 Popup.js 中,您可以调用从父级传递的方法为

onSubmit = {this.props.handleSubmit}

我创建了一个CodeSandBox 来演示数据从父组件到子组件的流动,反之亦然

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2019-09-08
    • 1970-01-01
    • 2017-08-23
    • 2019-04-03
    • 2015-12-30
    • 2019-10-08
    相关资源
    最近更新 更多