【发布时间】:2018-06-18 03:35:08
【问题描述】:
我知道如何使用一个输入文本字段创建名称列表。如何创建具有名字输入字段和姓氏输入字段的人员列表。因此,您如何使用由姓氏和名字组成的多个输入值来创建人员列表。我如何在 react.js 中做到这一点?
- 约翰·卡特
- 亚当·韦斯特
- 马克·哈米尔
- 斯坦·李
- 彼得·帕克
- 克拉克·肯特
现在,我现在才知道如何只使用一个输入字段来创建如下列表:
- 约翰
- 亚当
- 马克
- 斯坦
- 彼得
- 克拉克
此时不需要每个名称前的点。
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
function PostButton(props){
var style = {
width:24,
height:24
}
return (
<button style = {style} onClick = { () => props.handleClick()}>{props.label}</button>
)
}
function PostText(props){
var style = {
border:"1px solid black",
width: props.width
}
return (
<div style = {style}>{props.text}</div>
)
}
function Post(props){
var style = {
display:"flex"
}
return (
<div style = {style}>
<PostButton label = "x" handleClick = {props.removeItem}/>
<PostTextFirstName text = {props.firstName} width = "200"/>
<PostTextLastName text = {props.lastName} width = "200" />
</div>
)
}
function PostList(props){
return (
<ol>
{
props.postList.map((item,index) =>
<Post key = {index}
firstName = {item.firstName}
lastName = {item.lastName}
removeItem = {() => props.removeItem(index)}
/>
)
}
</ol>
)
}
class App extends React.Component{
constructor(props){
super(props)
this.state = {value:"", items : []}
}
handleChange(event){
this.setState({value:event.target.value})
console.log(this.state.value)
}
addItem()
{
var itemsCopy = this.state.items.slice()
var truncatedString = this.state.value.substring(0,20);
itemsCopy.push({"firstName":truncatedString})
this.setState({items:itemsCopy,value:""})
}
removeItem(index)
{
var itemsCopy = this.state.items.slice()
itemsCopy.splice(index,1);
this.setState({items:itemsCopy})
}
render(){
return (
<div>
<div>First Name</div>
<input value = {this.state.value} onChange = {this.handleChange.bind(this)}/>
<div>Last Name</div>
<input value = {this.state.value} onChange = {this.handleChange.bind(this)}/>
<button onClick = { () => this.addItem()}>Submit</button>
<PostList postList = {this.state.items}
removeItem = {this.removeItem.bind(this)}
/>
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById("root")
)
【问题讨论】:
-
不确定我是否理解您的问题。您想根据表单的连续提交创建人员列表(名字 + 姓氏),还是希望能够将新的名字/姓氏输入字段对附加到您的表单中?
-
我在问题中添加了更多细节。我知道如何通过单个输入字段添加名字并建立一个名字列表。如何使用名字的输入字段和姓氏的输入字段来建立具有名字和姓氏的人员列表。我只知道如何使用一个输入字段。我不知道如何使用两个输入字段来做到这一点。我需要建立一个包含名字和姓氏的人员列表,而不仅仅是他们的名字。
标签: reactjs