Form errors with handleInputChange in component

你离开我真会死。 提交于 2019-12-13 21:47:07

问题


I'm using map to loop over an array of objects. I'm using this data to populate a form however I'm having trouble with the handleInputChange function. How do I initiate handleInputChange when I'm using a components. The error I get is this.setState is not a function at handleInputChange

Path: formComponent.jsx

   return (
      <li>
        <SingleInput
          inputType={'text'}
          title={'Company name'}
          name={'position.company'}
          controlFunc={this.props.handleInputChange}
          content={this.props.company}
          placeholder={'Company name'}
          bsSize={null}
        />

      </li>
    );

CareerHistoryPositionsUpdateForm.propTypes = {
  company: PropTypes.string,
  title: PropTypes.string,
  controlFunc: PropTypes.string
};

Path: `form.jsx'

handleInputChange(event) {
  const target = event.target;
  const value = target.type === 'checkbox' ? target.checked : target.value;
  const name = target.name;

  this.setState({
    [name]: value
  });
}

renderPositions() {
  const profileCandidateCollection = this.props.profileCandidate;
  const careerHistoryPositions = profileCandidateCollection && profileCandidateCollection.careerHistoryPositions;
  if (careerHistoryPositions) {
    return careerHistoryPositions.map((position) => {

      return (
        <CareerHistoryPositionsUpdateForm
          key={position.uniqueId}
          company={position.company}
          controlFunc={this.handleInputChange}
        />
      )
    })
  }
}

render() {
  return (
    <form className="careerHistoryForm" onSubmit={this.handleFormSubmit}>
      <ul>
        <p>Test</p>
        {this.renderPositions()}
      </ul>

      <input type="submit" className="btn btn-primary" value="Save" />
    </form>
  );
}

回答1:


You need to bind handleInputChange to the instance of the component so this inside the function references the expected object when it's called:

class YourComponent extends React.Component {
  constructor(props) {
    super(props)
    this.handleInputChange = this.handleInputChange.bind(this)
  }
}

If you're using babel-preset-stage-2 (or using tooling which configures the necessary Babel plugin for you, such as create-react-app), you can use this slightly nicer syntax to bind the function when you're defining it:

class YourComponent extends React.Component {
  handleInputChange = (event) => {
    // ...
  }
}


来源:https://stackoverflow.com/questions/44534473/form-errors-with-handleinputchange-in-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!