【发布时间】: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 的新手,所以请多多包涵。
提前致谢。
【问题讨论】:
-
有人在下面的链接中回答了这个问题。请尝试一次。 stackoverflow.com/questions/49313030/…
标签: reactjs components parameter-passing onsubmit