使用组件中的handleInputChange形成错误

时间:2017-06-14 02:34:15

标签: reactjs this

我使用map循环遍历一个对象数组。我使用此数据填充表单,但我遇到了handleInputChange功能问题。我在使用组件时如何启动handleInputChange。我得到的错误是this.setState is not a function at handleInputChange

路径: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
};

路径:`form.jsx&#39;

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 个答案:

答案 0 :(得分:0)

您需要bind handleInputChange到组件的实例,因此函数内的this会在调用时引用预期的对象:

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

如果您正在使用babel-preset-stage-2(或使用为您配置必要的Babel插件的工具,例如create-react-app),您可以使用此slightly nicer syntax绑定该功能当你定义它时:

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