javascript - 使用来自不同组件的值设置状态
问题描述
我的 App.js 类中有一组书籍对象
{ id: 1,title: "How to Learn JavaScript - Vol 1", info: "Study hard"},
{ id: 2,title: "How to Learn ES6", info: "Complete all exercises :-)"},
{ id: 3,title: "How to Learn React",info: "Complete all your CA's"},
{ id: 4,title: "Learn React", info: "Don't drink beers, until Friday (after four)"
}
我想制作一个新组件,我可以在其中添加新的书籍对象。
import React, { Component } from 'react'
export default class AddBook extends Component {
state={
title: '',
info: ''
}
render() {
return (
<div>
<input type="text" placeholder="title" value={this.state.title} onChange={(e) =>{this.setState({title: e.target.value})}}>Enter title</input>
<input type="text" placeholder="title" value={this.state.info} onChange={(e) =>{this.setState({info: e.target.value})}}>Enter Info</input>
<button onClick={this.props.addBook(this.state.title, this.state.info)}>Submit</button>
</div>
)
}
}
我想将表单中的值传递回 App.js,这样我就可以将一个对象添加到我的书籍数组中。
解决方案
这是您的 App.js:
import React from 'react';
import Form from './Form';
export default class App extends React.Component {
state = { books: [] };
addBook = book => {
this.setState({ books: [book, ...this.state.books] });
};
render() {
return (
<div>
<Form addBook={this.addBook} />
{this.state.books.map(book => {
return (
<div key={book.id}>
<div>Title: {book.title}</div>
<div>Info: {book.info}</div>
</div>
);
})}
</div>
);
}
}
这是你的 Form.js:
import React from 'react';
export default class Form extends React.Component {
state = { title: '', info: '' };
generateId = () =>
Math.random()
.toString(36)
.substr(2, 10);
handleChange = event => {
this.setState({
[event.target.name]: event.target.value,
});
};
handleSubmit = event => {
event.preventDefault();
this.props.addBook({
id: this.generateId(),
title: this.state.title,
info: this.state.info,
});
this.setState({ title: '', info: '' });
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="title"
value={this.state.title}
onChange={this.handleChange}
/>
<input
type="text"
name="info"
value={this.state.info}
onChange={this.handleChange}
/>
<input type="submit" />
</form>
);
}
}
尝试剖析它并弄清楚它是如何工作的......如果你有问题问......
推荐阅读
- azure - Azure B2C 安全 API MFA
- android - 为 Espresso 测试全局禁用非 Animator 动画
- c++ - 如何仅在括号之间匹配未嵌套的组?
- nlp - 为什么服装动作不起作用 - Rasa Core
- ruby - 在 HTTParty 发布请求中将数组作为正文发送:未定义的方法 `bytesize' for #
我正在尝试使用 httparty gem 发出帖子请求。
response = HTTParty.post(App.base_uri + "/api?service=post&action=update&version=2", body: [{"some_big_json": "w
- javascript - 我想在注册信用卡时禁用谷歌支付
- python - 尝试在加载的 QPixMap 图像上绘制时崩溃
- java - 如何在 Java 中声明一个 uint8_t 数组
- jenkins - 如何在 Jenkins 中使用作业参数或环境变量来归档工件?
- python - 如何向 csv 文件的行添加值?