gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'value' of undefined on components (ReactJS forms)

转载 作者:行者123 更新时间:2023-12-01 01:31:46 24 4
gpt4 key购买 nike

这不是 this 的重复项,因为我使用的是受控组件,因此它应该有 target.value 。我按照给出的示例 here 收到此错误,我知道我没有将 onClick 和 onSubmit 与 'this' 绑定(bind),(代码在绑定(bind)上运行良好),但我已将 'this.handleChange' 更改为箭头函数 '() => this.handleChange()' 并且对于handleSubmit 类似。这应该按照给定的方式工作 here

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";

class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
}

handleChange(event) {
this.setState({
value: event.target.value
});
}

handleSubmit(event) {
alert("event was submitted" + this.state.value);
event.preventDefault();
}

render() {
return (
<form onSubmit={() => this.handleSubmit()}>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={() => this.handleChange()}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}


ReactDOM.render(<NameForm />, document.getElementById("root"));

最佳答案

您没有将事件传递给事件处理程序。将 onChange={() => this.handleChange()} 更改为 onChange={(e) => this.handleChange(e)}

此外,它应该是 this.setState({value: event.target.value}) 而不是 this.setState({event.target.value})

class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
}

handleChange(event) {
this.setState({
value: event.target.value
});
}

handleSubmit(event) {
alert("event was submitted" + this.state.value);
event.preventDefault();
}

render() {
return (
<form onSubmit={() => this.handleSubmit()}>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={(e) => this.handleChange(e)}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}

ReactDOM.render(<NameForm />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

关于javascript - 类型错误 : Cannot read property 'value' of undefined on components (ReactJS forms),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53222951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com