微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我试图做一个可重用的组件,选择图像并获取binairy数据我正在努力在另一个组件中使用该数据

如何解决我试图做一个可重用的组件,选择图像并获取binairy数据我正在努力在另一个组件中使用该数据

    Getting data in the console but want to import the var image to be used in another component
    Example would be to  do this in another component

,然后将图像var发送为wel 问题是我的组件如何即时返回数据,还是问题我的组件如何即时返回数据,还是问题我的组件如何即时返回数据,还是 //////////////////////////////////////////////////// //////////////////////////////////////////////// 从'react'导入React,{useState}; 从“ axios”导入axios;

    export default function logoUpload() {
        const [image,setimage] = useState(''); //Wnat to export this variable
        const [selectedFile,setSelectedFile] = useState('');
        const fileUpload = React.createRef();
    
        function onFileChangeHandler(e) {
            // routine to run when the user selects a file to upload as an image
            e.preventDefault();
            const file = e.target.files[0];
            var promise = new Promise((resolve,reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = e => reject(e);
            });
            promise.then(response => {
                setimage(response);
                setSelectedFile(file);
                    console.log(response);
            });
        }
    
         function showFileUpload(e) {
            e.preventDefault();
            fileUpload.current.click();
            return image;
        }
    
// export this function dont kNow how :(
        function getimageData() {
            return image;
        }
    
        return (
//Click and display image and get data
            <div className="AddImage">
                <input
                    type="file"
                    id="imageUpload"
                    style={{ display: 'none' }}
                    ref={fileUpload}
                    onChange={onFileChangeHandler}
                />
    
                <input
                    type="image"
                    style={{
                        width: '100px',height: '100px',borderRadius: '50%',objectFit: 'cover',objectPosition: 'center',}}
                    src={image}
                    alt="Add logo"
                    onClick={showFileUpload}
                />
            </div>
            
        );
    }

解决方法

管理父组件中的状态,并将其作为道具传递给LogoUpload Function

export default function LogoUpload(image,setImage) {
 ...
}

class ParentComponent: React.FC = () => {
  const [image,setImage] = useState('');
  
  return (
    ...
    <LogoUpload image={image} setImage={setImage} />
    ...
  );
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。