【发布时间】:2020-11-15 14:05:53
【问题描述】:
我是 React 的新手,我正在尝试使用表单组件中的数据并使用该数据调用另一个名为 Fruits 的组件中的函数。对于我所阅读的内容,我必须通过道具来完成,但实际上我很难做到。
我有一个水果列表,我希望用户能够插入他最喜欢的水果。我有 3 个组件 Form、Fruits、Fruit 和 App。我认为最好的方法是在 Fruits 组件中添加一个函数 addNewFruit(),但我不知道如何将 Form 组件中的数据(存储在 newFruit 中)发送到 Fruits 组件。
代码如下:
import React from "react";
import Fruits from "./Fruits";
import Form from "./Form";
function App() {
return (
<div className="App">
<h1>List of fruits</h1>
<p>enter your favourite fruit</p>
<Form />
<Fruits />
</div>
);
}
export default App;
表单组件
import React, { Component } from "react";
class Form extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
rating: "",
};
}
handlerName = (event) => {
console.log(event.target.value);
this.setState({
name: event.target.value,
});
};
handlerRating = (event) => {
console.log(event.target.value);
this.setState({
rating: event.target.value,
});
};
handlerSubmit = (event) => {
event.preventDefault();
const newFruit = this.state;
};
render() {
return (
<div>
<form onSubmit={this.handlerSubmit}>
<input
type="text"
placeholder="name"
value={this.state.name}
onChange={this.handlerName}
/>
<input
type="number"
placeholder="rating"
value={this.state.rating}
onChange={this.handlerRating}
/>
<button type="submit">Submit fruit</button>
</form>
</div>
);
}
}
export default Form;
水果成分
import React, { Component } from "react";
import Fruit from "./Fruit";
class Fruits extends Component {
constructor(props) {
super(props);
this.state = {
fruits: [
{ name: "Orange", rating: 6 },
{ name: "Banana", rating: 7 },
{ name: "Kiwi", rating: 9 },
],
};
}
render() {
const fruits = this.state.fruits.map((fruit) => (
<Fruit name={fruit.name} rating={fruit.rating} />
));
return fruits;
}
}
export default Fruits;
水果
import React, { Component } from "react";
class Fruit extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<p>
{" "}
The name of the fruit is {this.props.name} and its rating is{" "}
{this.props.rating}
</p>
);
}
}
export default Fruit;
【问题讨论】:
-
要形成能够调用fruit的形式,您需要设置一个高阶函数并将其作为道具传递,以便在执行时传递。 Fruit 会监听它并获取一个值或一个函数调用。
-
但我想访问水果组件中的表单内容,而不是其他方式。以及如何在不返回 的情况下访问该表单数据?
标签: javascript reactjs components