如何在Reaction组件中使用wp媒体上传库?

时间:2020-06-04 作者:Mahdi Akrami

我正在使用create-react-app 为wordpress编写react插件。我想在插件管理设置页面中添加一个按钮,用于上传图像。我遵循此文档,但没有呈现任何内容。

https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/media-upload
my code:

...
import { Button } from \'@wordpress/components\';
import { MediaUpload, MediaUploadCheck } from \'@wordpress/block-editor\';

const ALLOWED_MEDIA_TYPES = [ \'image\' ];

const MyMediaUploader = () => {
    return (
        <MediaUploadCheck>
            <MediaUpload
                onSelect={ ( media ) => console.log( \'selected \' + media.length ) }
                allowedTypes={ ALLOWED_MEDIA_TYPES }
                value=""
                render={ ( { open } ) => (
                    <Button onClick={ open }>
                        Open Media Library
                    </Button>
                ) }
            />
        </MediaUploadCheck>
    );
}

export default function settingsPage(){
    return(
        <MyMediaUploader/> 
    )
}

1 个回复
SO网友:Tushar Imran

这是我的解决方案

import React, { useState, useEffect } from \'react\'
import _ from \'lodash\'
export default function FeaturedImage(props) {
_.noConflict()
let frame
const runUploader = (event) => {
    event.preventDefault()

    // If the media frame already exists, reopen it.
    if (frame) {
        frame.open()
        return
    }

    // Create a new media frame
    frame = wp.media({
        title: \'Select or Upload Media Of Your Chosen Persuasion\',
        button: {
            text: \'Use this media\',
        },
        multiple: false, // Set to true to allow multiple files to be selected
    })

    // Finally, open the modal on click
    frame.open()
}
return (
    <React.Fragment>
        <button type=\'button\' onClick={runUploader}>
            Open Uploader
        </button>
    </React.Fragment>
)
}

相关推荐

禁用jQuery javascript的Cloudflare Rocket Loader并使其首先加载

我使用Cloudflare Rocket Loader在我的站点上加速Javascript。问题是,它在加载jQuery本身之前加载某些需要jQuery的脚本,使它们无法正常工作。尽快禁用Rocket Loader以添加特定脚本data-cfasync=\"false\" 到<script src=\"\"> 我想知道如何将其添加到jQuery脚本中,因为Wordpress并不是简单地通过脚本标记加载jQuery。目前我的网站加载jquery-migrate.min.js 和jquery.js