创建具有一些功能方面的虚拟网站。为了澄清,我一周前开始学习React,所以请善意回答你的问题。谢谢!
最初在App.js中创建了一个允许我添加和删除客户端的状态。 (像老板待办事项清单)
现在使用一个不同的组件,我可以“添加课程”,我想有一个下拉选择器,我可以选择其他状态的现有客户端作为我的选项。到目前为止,我已经创建了所有内容以获取输入和console.log()显示一切正常。但是,我似乎无法将下拉选项显示为现有客户端,因此我可以将课程添加到其他状态。澄清我有2个州,客户和课程(与现有客户)。
这是我的App.js
import React, { Component } from 'react'
import Clients from './components/Clients'
import AddClient from './components/AddClient'
import NavBar from './components/NavBar'
import AddLesson from './components/AddLesson'
class App extends Component {
state = {
clients : [
{id : 1 , name : 'bob', price : 30},
{id : 2 , name : 'mary', price : 40},
{id : 3 , name : 'greg', price : 45}
],
lessons : [
{id: null, name: '', time: null}
]
}
deleteClient = (id) => {
let clients = this.state.clients.filter(client => {
return client.id !== id
})
this.setState({
clients: clients
})
}
addClient = (newClient) => {
newClient.id = Math.random();
let clients = [...this.state.clients, newClient];
clients.sort((a, b) => a.name.localeCompare(b.name))
this.setState({
clients: clients,
})
}
addLesson = (newLesson) => {
newLesson.id = Math.random();
let lessons = [...this.state.lessons, newLesson];
this.setState({
lessons: lessons,
})
console.log(lessons)
}
render() {
return (
<div className="App">
<NavBar/>
<Clients clients={this.state.clients} deleteClient={this.deleteClient}/>
<AddClient addClient={this.addClient}/>
<AddLesson addLesson={this.addLesson}/>
</div>
);
}
}
export default App;
这是AddLesson.js
import React, {Component} from 'react'
class AddLesson extends Component {
state = {
lessons: [
{id : null, name: '', time: null}
]
}
handleChange = (e) => {
this.setState({
[e.target.id] : e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault();
this.props.addLesson(this.state);
e.target.reset();
}
render() {
return (
<div className="text-center">
<h2>Add a lesson</h2>
<form onSubmit={this.handleSubmit}>
<select name="lesson_client">
<option>{this.props.clients}</option>
</select>
{/* <label htmlFor="name">Client Name: </label>
<input type="text" id="name" onChange={this.handleChange}/><br/>
<label htmlFor="time">Lesson Duration (in hours): </label>
<input type="text" id="time" onChange={this.handleChange}/><br/>
<button className="btn btn-primary">Add Client</button> */}
</form>
</div>
)
}
}
export default AddLesson
我试着不要重载代码,所以如果我遗漏了什么,请告诉我,我会编辑它。
您需要遍历客户端并呈现它们。
<select onChange={(e) => this.handleChange(e)} name="lesson_client">
{this.props.clients.map(client => <option key={client.id} value={client.price}>{client.name}</option>)}
</select>
你可以听qazxsw poi来阅读所选的值。 (注意:我已经将qazxsw poi更改为qazxsw poi,因为select tag上没有id attr)
handleChange
而且我也注意到你没有将e.target.id
传递给e.target.name
组件。请传递它以使代码生效。
handleChange = (e) => {
this.setState({
[e.target.name] : e.target.value
})
}