我目前正试图从我看到的使用钩子的示例中编写一个类,但我无法使其正常工作。有人能帮我吗?这是代码。它在React中动态添加了一个字段。错误显示:./src/App.js第27:34行:未定义"handleInputChange"无undef第34:34行:未定义"handleInputChange"没有undef第38:36行:未定义"handleAddClick"没有定义
import React from "react";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
inputList: [{ firstName: "", lastName: "" }]
};
this.handleAddClick = this.handleAddClick.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
// handle input change
handleInputChange = (e, index) => {
const { name, value } = e.target;
const list = [...this.state.inputList];
list[index][name] = value;
this.setState({ inputList: list });
}
// handle click event of the Add button
handleAddClick = () => {
this.setState({
inputList: [...this.state.inputList, { firstName: '', lastName: '' }]
});
}
render() {
return (
<div className="App" >
{
this.state.inputList.map((x, i) => {
return (
<div className="box">
<input
name="firstName"
placeholder="Enter First Name"
value={x.firstName}
onChange={e => handleInputChange(e, i)}
/>
<input
className="ml10"
name="lastName"
placeholder="Enter Last Name"
value={x.lastName}
onChange={e => handleInputChange(e, i)}
/>
<div className="btn-box">
<button onClick={handleAddClick}>Add</button>}
</div>
</div>
);
})
}
< div style={{ marginTop: 20 }}> {JSON.stringify(this.state.inputList)}</div >
</div >
);
}
}
以下是使用钩子的代码,它运行良好:https://www.cluemediator.com/add-or-remove-input-fields-dynamically-with-reactjs
用this
调用它
<button onClick={this.handleAddClick}>Add</button>}
访问类组件中的函数时需要使用this