javascript - 如何渲染类组件?
问题描述
我正在为使用uploadProductPage.js 和uploadProductPageClassComponents.js 的网站开发样板文件。我想让网站显示一个 dropzone 框,这样我就可以将图像上传到 amazon s3,但是每当我尝试渲染它时,它都会给我一个错误,即“onDrop”未定义。如何定义类组件以呈现它?
代码:uploadProductPage.js
import React, { useState } from 'react'
import { Typography, Button, Form, message, Input, Icon } from 'antd';
import FileUpload from '../../utils/FileUpload'
import Axios from 'axios';
import Dropzone from 'react-dropzone';
import download from './download.jpeg'
const { Title } = Typography;
const { TextArea } = Input;
const Continents = [
{ key: 1, value: "1" },
{ key: 2, value: "2" },
{ key: 3, value: "3" },
{ key: 4, value: "4" },
{ key: 5, value: "5" },
{ key: 6, value: "6" },
{ key: 7, value: "7" }
]
function UploadProductPage(props) {
const [TitleValue, setTitleValue] = useState("")
const [DescriptionValue, setDescriptionValue] = useState("")
const [PriceValue, setPriceValue] = useState(0)
const [ContinentValue, setContinentValue] = useState([])
const [Images, setImages] = useState([])
const onTitleChange = (event) => {
setTitleValue(event.currentTarget.value)
}
const onDescriptionChange = (event) => {
setDescriptionValue(event.currentTarget.value)
}
const onPriceChange = (event) => {
setPriceValue(event.currentTarget.value)
}
const onContinentsSelectChange = (event) => {
setContinentValue(event.currentTarget.value)
}
const updateImages = (newImages) => {
setImages(newImages)
}
///////// on drop stuff
const onSubmit = (event, files) => {
event.preventDefault();
if (!TitleValue || !DescriptionValue || !PriceValue ||
!ContinentValue || !Images) {
return alert('fill all the fields first!')
}
const variables = {
writer: props.user.userData._id,
title: TitleValue,
description: DescriptionValue,
price: PriceValue,
images: Images,
continents: ContinentValue,
}
Axios.post('/api/product/uploadProduct', variables)
.then(response => {
if (response.data.success) {
alert('Product Successfully Uploaded')
props.history.push({
pathname: "/user/cart",
state: {
data: variables,
},
})
} else {
alert('Failed to upload Product')
}
})
const data = new FormData();
if ( this.state.selectedFile )
{data.append( 'profileImage', this.state.selectedFile, this.state.selectedFile.name );
Axios.post( '/api/profile/profile-img-upload', data, {
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
}
})
.then( ( response ) => {if ( 200 === response.status ) {
// If file size is larger than expected.
if( response.data.error ) {
if ( 'LIMIT_FILE_SIZE' === response.data.error.code ) {
this.ocShowAlert( 'Max size: 2MB', 'red' );
} else {
console.log( response.data );// If not the given file type
this.ocShowAlert( response.data.error, 'red' );
}
} else {
// Success
let fileName = response.data;
console.log( 'fileName', fileName );
this.ocShowAlert( 'File Uploaded', '#3089cf' );
}
}
}).catch( ( error ) => {
// If another error
this.ocShowAlert( error, 'red' );
});
} else {
// if file not selected throw error
this.ocShowAlert( 'Please upload file', 'red' );
}
}
return (
<div style={{ maxWidth: '700px', margin: '2rem auto' }}>
<div style={{ textAlign: 'center', marginBottom: '2rem' }}>
<Title level={2}> Upload Prompt </Title>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
</div>
<Form onSubmit={onSubmit} >
{/* DropZone */}
<Dropzone
onDrop={this.onDrop}
multiple={false}
maxSize={800000000}
>
{({ getRootProps, getInputProps }) => (
<div style={{
width: '300px', height: '240px', border: '1px solid lightgray',
display: 'flex', alignItems: 'center', justifyContent: 'center'
}}
{...getRootProps()}
>
{console.log('getRootProps', { ...getRootProps() })}
{console.log('getInputProps', { ...getInputProps() })}
<input {...getInputProps()} />
<Icon type="plus" style={{ fontSize: '3rem' }} />
</div>
)}
</Dropzone>
<br />
<br />
<label>Subject</label>
<Input
onChange={onTitleChange}
value={TitleValue}
/>
<br />
<br />
<label>Title</label>
<Input
onChange={onDescriptionChange}
value={DescriptionValue}
/>
<br />
<br />
<label>Pages</label>
<Input
onChange={onPriceChange}
value={PriceValue}
type="number"
/>
<br /><br />
<label>Due Date</label>
<br /><br />
<Input onChange={onContinentsSelectChange} value={ContinentValue}
type="date"
/>
<br />
<br />
<Button
onClick={onSubmit}
>
Submit
</Button>
</Form>
</div>
)
}
export default UploadProductPage
上传ProductPageClassComponents.js
import React, { Component } from 'react'
import { Typography, Button, Form, Input } from 'antd';
import axios from 'axios';
import FileUpload from '../../utils/FileUpload';
import Dropzone from 'react-dropzone';
const { Title } = Typography;
const { TextArea } = Input;
const Continents = [
{ key: 1, value: "Africa" },
{ key: 2, value: "Europe" },
{ key: 3, value: "Asia" },
{ key: 4, value: "North America" },
{ key: 5, value: "South America" },
{ key: 6, value: "Australia" },
{ key: 7, value: "Antarctica" }
]
export class UploadProductPage extends Component
{constructor( props ) {
super( props );
this.state = {
selectedFile: null,
selectedFiles: null
}
onDrop = ( event ) => {
this.setState({
selectedFile: event.target.files[0]
});
let formData = new FormData();
const config = {
header: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': `multipart/form-data; boundary=${formData._boundary}`
}
}
formData.append("profileImage", files[0])
//save the Image we chose inside the Node Server
}
onDelete = (image) => {
const currentIndex = Images.indexOf(image);
let newImages = [...Images]
newImages.splice(currentIndex, 1)
setImages(newImages)
props.refreshFunction(newImages)
}
state = {
title: '',
description: '',
continents: [],
images: [],
price: []
}
handleChangeTitle = (event) => {
this.setState({ title: event.currentTarget.value })
}
handleChangePrice = (event) => {
this.setState({ price: parseInt(event.currentTarget.value, 10) })
}
handleChangeDecsription = (event) => {
// console.log(event.currentTarget.value)
this.setState({ description: event.currentTarget.value })
}
handleChangeContinents = (event) => {
this.setState({ continents: event.currentTarget.value })
}
onSubmit = (event) => {
event.preventDefault();
if (this.props.user.userData && !this.props.user.userData.isAuth) {
return alert('Please Log in First')
}
if (!this.state.title || !this.state.description ||
!this.state.continents || !this.state.images
|| !this.state.price) {
return alert('Please first fill all the fields')
}
const variables = {
writer: this.props.user.userData._id,
title: this.state.title,
description: this.state.description,
images: this.state.images,
continents: this.state.continents,
price: this.state.price
}
axios.post('/api/product/uploadProduct', variables)
.then(response => {
if (response.data.success) {
alert('video Uploaded Successfully')
setTimeout(() => {
this.props.history.push('/')
}, 1000);
} else {
alert('Failed to upload video')
}
})
}
updateFiles = (newImages) => {
this.setState({ images: newImages })
}
}
render() {
return (
<div style={{ maxWidth: '700px', margin: '2rem auto' }}>
<div style={{ textAlign: 'center', marginBottom: '2rem' }}>
<Title level={2} > Upload Prompt </Title>
</div>
<Dropzone
onDrop={this.onDrop}
multiple={false}
maxSize={800000000}
>
{({ getRootProps, getInputProps }) => (
<div style={{
width: '300px', height: '240px', border: '1px solid lightgray',
display: 'flex', alignItems: 'center', justifyContent: 'center'
}}
{...getRootProps()}
>
{console.log('getRootProps', { ...getRootProps() })}
{console.log('getInputProps', { ...getInputProps() })}
<input {...getInputProps()} />
<Icon type="plus" style={{ fontSize: '3rem' }} />
</div>
)}
</Dropzone>
<div style={{ display: 'flex', width: '300px', height: '300px'}}>
{Images.map((image, index) => (
<div onClick={() => onDelete(image)}>
<img style={{ minWidth: '300px', width: '300px', height: '240px' }} src={download} alt={`productImg-${index}`} />
</div>
))}
</div>
<Form onSubmit={this.onSubmit}>
<FileUpload refreshFunction={this.updateFiles} />
<br /><br />
<label>Title</label>
<Input
onChange={this.handleChangeTitle}
value={this.state.title}
/>
<br /><br />
<label>Description</label>
<TextArea
onChange={this.handleChangeDecsription}
value={this.state.description}
/>
<br /><br />
<label>Price($)</label>
<Input
type="text"
onChange={this.handleChangePrice}
value={this.state.price}
/>
<br /><br />
<Input
type="date"
onChange={this.handleChangeContinents}>
value={this.state.continents}
))
</Input>
<br /><br />
<Button type="primary" size="large" onClick={this.onSubmit}>
Submit
</Button>
</Form>
</div>
)
}
}
export default UploadProductPage
解决方案
推荐阅读
- python - focusIn 和 focusOut 事件类型是什么意思?
- javascript - react-full-page 阻止我的页面以特定 ID 打开,例如 http://localhost:3000/#someIdWhereIWantThePageToBeOpened
- node.js - Angular 7、Node JS、IIS、pm2、ERR_CONNECTION_RESET 上传大文件时
- powershell - 使用十六进制值调用 WebRequest
- android - 使用Kotlin单击editText时如何修复NestedScrollView
- opencv - OpenCV 声称找到“错误”的 cuda 版本
- php - 在 WooCommerce 产品描述周围添加一个 div
- python - 类型错误:函数在 cv2.rectangle 函数中正好有 4 个参数(给定 2 个)
- r - 根据 R 中的时间范围对新变量进行分组
- c# - 将 tsv 文件中包含的文本打印到控制台的方法