javascript - AntDesign 和 React 问题
问题描述
如何使用 AntDesign 从一个组件到另一个组件获取值?
我有组件调用CreateProduct导入另一个 AntDesign 组件调用AddImage
AddImage 将图片上传到 Cloudinary 并获取上传图片的 url,这工作正常,但CreateProduct不更新值
我假设使用 useEffect 应该可以解决问题,但不确定如何实现
这是CreateProduct组件
import React, { useState, useEffect } from 'react';
import {
Form,
Button,
Input,
Select,
message,
Alert,
notification,
} from 'antd';
import { AddImage } from './AddImage.js';
import { createProduct } from '../../services/Products';
function CreateProductForm({ history }) {
const [img, setImg] = useState(null);
const [error, setError] = useState(null);
const openNotification = (placement, coincidencias) => {
notification.info({
message: `Coincidences found ${coincidencias}`,
description: `We have found ${coincidencias} wishes that may be coincidences of your product`,
placement,
});
};
async function handleFormSubmit(values) {
let send = true;
console.log(img);
// HERE I need to update img to ut in the values and send it to the Db
// values.image = img; /
//mensajes de campos vacios en form
Object.entries(values).map((val) => {
if (val[1] === undefined) {
message.error(`Add ${val[0].toUpperCase()} field is empty`);
send = false;
}
if (val[0] === 'price') {
setError(
'All the fields must be filled and the price must have numbers,not letters!'
);
let valor = Number(val[1]);
if (typeof valor !== 'number') {
send = false;
}
}
});
if (send) {
let { data } = await createProduct(values);
if (data.wishCoincidences.length > 0) {
openNotification('bottomRight', data.wishCoincidences.length);
} //mensajes de coincidencias
history.push('/MyProducts');
message.success(`${data.name} created`);
}
}
return (
<>
<Form layout="vertical" onFinish={handleFormSubmit}>
<h1>Create your product!</h1>
{error && <Alert message={error} type="error" />}
<Form.Item name="name" label="Title:">
<Input />
</Form.Item>
<Form.Item name="description" label="Description:">
<Input />
</Form.Item>
<Form.Item name="price" label="Price:">
<Input />
</Form.Item>
<Form.Item name="image" label="Image:">
{/* This returns img, which is an url, how do I get it?*/}
<AddImage />
{img & img ? img : 'not reading img'}
</Form.Item>
<Form.Item name="category" label="category:">
<Select initialvalue="" style={{ width: '20%' }}>
<Select.Option value="books">Books</Select.Option>
<Select.Option value="electronics">Electronics</Select.Option>
<Select.Option value="clothes">Clothes</Select.Option>
<Select.Option value="other">Other</Select.Option>
</Select>
</Form.Item>
<Button type="primary" block size="middle" htmlType="submit">
Create
</Button>
</Form>
</>
);
}
export default CreateProductForm;
这是AddImage组件
import { Upload } from 'antd';
import React, { useState } from 'react';
import axios from 'axios';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
const cloudinaryAPI =
'https://api.cloudinary.com/**********************/upload';
export const AddImage = () => {
const [img, setImg] = useState(null);
const [loading, setLoading] = useState(null);
const [error, setError] = useState(null);
async function handleUploadFile(file) {
try {
setLoading(true);
const data = new FormData();
//esto sube a el archivo a cloudinary
data.append('file', file);
data.append('upload_preset', 'uploadfilestiendaDeGarage');
//esto manda al backend? me manda CORS
const {
data: { secure_url },
} = await axios.post(cloudinaryAPI, data);
setImg(secure_url);
setLoading(false);
} catch (e) {
console.dir(e.response.data.message);
setError(e.response.data.message);
}
}
const uploadButton = (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div style={{ marginTop: 8 }}>Upload</div>
</div>
);
return (
<>
<Upload
name="avatar"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
beforeUpload={handleUploadFile}
// action={() => alert(img)}
>
{img ? (
<img src={img} alt="pic" style={{ width: '50%' }} />
) : (
uploadButton
)}
</Upload>
</>
);
};
您可以在此处查看我想要实现此功能的应用程序的实时版本
解决方案
CreateProduct
对于图像状态,您在和组件中具有相同的名称,AddImage
因此请尝试更改状态名称,CreateProduct
如下所示:-
const [imgUrl, setImgUrl] = useState(null);
在组件setImgUrl
中作为道具传递AddImage
<AddImage setImgUrl={(url) => setImgUrl(url)}/>
提取setImgUrl
并AddImage
使用handleUploadFile
如下:-
export const AddImage = ({setImgUrl}) => {
const [img, setImg] = useState(null);
const [loading, setLoading] = useState(null);
const [error, setError] = useState(null);
async function handleUploadFile(file) {
try {
setLoading(true);
const data = new FormData();
//esto sube a el archivo a cloudinary
data.append('file', file);
data.append('upload_preset', 'uploadfilestiendaDeGarage');
//esto manda al backend? me manda CORS
const {
data: { secure_url },
} = await axios.post(cloudinaryAPI, data);
setImg(secure_url);
setImgUrl(secure_url); // use function here to set image url
setLoading(false);
} catch (e) {
console.dir(e.response.data.message);
setError(e.response.data.message);
}
}
const uploadButton = (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div style={{ marginTop: 8 }}>Upload</div>
</div>
);
return (
<>
<Upload
name="avatar"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
beforeUpload={handleUploadFile}
// action={() => alert(img)}
>
{img ? (
<img src={img} alt="pic" style={{ width: '50%' }} />
) : (
uploadButton
)}
</Upload>
</>
);
};
所以现在imgUrl
会有图像 url,你可以在CreateProduct
组件中使用它。
推荐阅读
- visual-studio-2017 - 使用固定选项卡时 SQL Server Management Studio 17.9 崩溃
- deployment - 站点发布错误(路由表中没有与提供的值匹配的路由。)
- wpf - 在 WPF 中使 Button 内的内容响应式
- javascript - 循环遍历数组中的对象并求和
- mysql - 如果记录尚不存在,则插入记录的有效方法,如果确实存在,则获取ID并将其用作外键?
- python - 从 python 调用外部命令,既不使用 os.system 也不使用子进程
- xamarin - 如何跳过一些堆栈以使后退按钮转到主页?
- spring - 使用spring cloud数据流,尝试部署一个简单的工作,但是卡住了,部署没有完成
- delphi - 在 Delphi 中添加单元或新表单会导致访问冲突
- javascript - 我想知道谷歌的网站翻译器可以在我们的网站上免费使用吗?在我们的网站上使用它还有其他顾虑吗?