问题描述
限时送ChatGPT账号..我正在使用 map 来遍历对象数组.我正在使用这些数据来填充表单,但是我在使用 handleInputChange
函数时遇到了问题.使用组件时如何启动 handleInputChange
.我得到的错误是 this.setState is not a function at handleInputChange
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
路径:formComponent.jsx
return (
<li>
<SingleInput
inputType={'text'}
title={'Company name'}
name={'positionpany'}
controlFunc={this.props.handleInputChange}
content={this.propspany}
placeholder={'Company name'}
bsSize={null}
/>
</li>
);
CareerHistoryPositionsUpdateForm.propTypes = {
company: PropTypes.string,
title: PropTypes.string,
controlFunc: PropTypes.string
};
路径:`form.jsx'
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={positionpany}
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>
);
}
推荐答案
您需要 bind handleInputChange
到组件的实例所以 this
函数内部在调用时引用了预期的对象:
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)
}
}
<小时>
如果你使用 babel-preset-stage-2
(或使用工具为您配置必要的 Babel 插件,例如 create-react-app),你可以使用这个稍微好一点的语法 在定义函数时绑定它:
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) => {
// ...
}
}
这篇关于组件中 handleInputChange 的表单错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论