反应。输入的通用处理程序

问题描述 投票:2回答:1

我有一个组件:

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的新手。我无法理解我的错误在哪里......我该怎么办?

reactjs react-native
1个回答
2
投票

firstNamelastName属性是您所在州的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>
© www.soinside.com 2019 - 2024. All rights reserved.