我正在尝试在ReactJS中制作一个文件组件。
我这样做:
import React from 'react';
export class InputTxt extends React.Component {
constructor(props) {
super(props);
this.state = {
file: null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
}
onChange(e) {
this.setState({
file: e.target.files[0]
})
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
但是我收到了:
TypeError:无法读取未定义的属性“ bind”
在此行:
this.onFormSubmit = this.onFormSubmit.bind(this)
为什么我会收到此错误?
答案 0 :(得分:1)
您缺少方法onFormSubmit
,这应该可以正常工作。
import React from 'react';
export class InputTxt extends React.Component {
constructor(props) {
super(props);
this.state = {
file: null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
}
onChange(e) {
this.setState({ file: e.target.files[0] })
}
onFormSubmit() {
console.log("Form submitted")
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}