名字:
handleFirstName(e) {
let value = e.target.value;
this.setState(prevState => ({
newUser: {
...prevState.newUser,
name: value
}
}));
}
姓氏:
handleLastName(e) {
let value = e.target.value;
this.setState(prevState => ({
newUser: {
...prevState.newUser,
name: value
}
}));
}
如何在React js中连接名字和姓氏?有人可以帮我实现fullName的方法吗?
答案 0 :(得分:3)
有几种获取fullName的方法,除了可以在方法中添加名称,还可以添加firstName和lastName,然后编写方法getFullName()
来访问它,并确保已定义newUser处于状态
import React, { Component } from "react";
class User extends Component {
state = {
newUser: { firstName: "", lastName: "" }
};
handleFirstName(e) {
let value = e.target.value;
this.setState(prevState => ({
newUser: {
...prevState.newUser,
firstName: value
}
}));
}
handleLastName(e) {
let value = e.target.value;
this.setState(prevState => ({
newUser: {
...prevState.newUser,
lastName: value
}
}));
}
getFullName() {
return this.state.newUser.firstName + " " + this.state.newUser.lastName;
}
render() {
return (
<div>
<input
type="text"
onChange={this.handleFirstName.bind(this)}
placeholder="Enter first Name"
/>
<input
type="text"
onChange={this.handleLastName.bind(this)}
placeholder="Enter last Name"
/>
FullName: {this.getFullName()}
</div>
);
}
}
export default User;
播放
答案 1 :(得分:0)
这也许就是您要寻找的东西:
this.setState(prevState => ({ fullName: [...prevState.fullName, { firstName: "", lastName: "" }]
请注意,fullName应该像这样:
fullName: [{firstName: "", lastName: ""}],