我有一个组件:
import React, { Component } from "react";
import BeforeSubmitScreen from "./beforeSubmitScreen.jsx";
class SignUpStepOne extends Component {
constructor(props) {
super(props);
this.state = {
isFormSubmitted: false,
newCustomer: {
firstName: "",
lastName: "",
email: "",
phone: "",
password: ""
}
};
}
handleInputChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
render() {
return (
<BeforeSubmitScreen
changed={this.handleInputChange}
customer={this.state.newCustomer}
/>
);
}
}
export default SignUpStepOne;
import React from "react";
const beforeSubmitScreen = props => {
return (
<>
<input
onChange={props.changed}
name="firstName"
value={props.customer.firstName}
/>
<input
onChange={props.changed}
name="lastName"
value={props.customer.lastName}
/>
</>
);
};
export default beforeSubmitScreen;
我需要使用通用处理程序为组件中的所有输入将输入与模型的属性绑定。
我是React的新手。我不知道我的错误在哪里... 我该怎么办?
答案 0 :(得分:2)
firstName
和lastName
属性在您的状态下是newCustomer
对象的一部分,但是您当前将其直接放在状态对象中。
将其放入newCustomer
对象中,它将按预期工作。
handleInputChange = e => {
const { name, value } = e.target;
this.setState(prevState => ({
newCustomer: { ...prevState.newCustomer, [name]: value }
}));
};
class SignUpStepOne extends React.Component {
constructor(props) {
super(props);
this.state = {
isFormSubmitted: false,
newCustomer: {
firstName: "",
lastName: "",
email: "",
phone: "",
password: ""
}
};
}
handleInputChange = e => {
const { name, value } = e.target;
this.setState(prevState => ({
newCustomer: { ...prevState.newCustomer, [name]: value }
}));
};
render() {
return (
<BeforeSubmitScreen
changed={this.handleInputChange}
customer={this.state.newCustomer}
/>
);
}
}
const BeforeSubmitScreen = props => {
return (
<React.Fragment>
<input
onChange={props.changed}
name="firstName"
value={props.customer.firstName}
/>
<input
onChange={props.changed}
name="lastName"
value={props.customer.lastName}
/>
</React.Fragment>
);
};
ReactDOM.render(<SignUpStepOne />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>