簡體   English   中英

從 React 組件內部加載 .css 文件

[英]Loading .css file from inside a component in React

我有一個組件,它通過componentDidMount()的 ajax 調用確定所需 .css 文件的位置,然后我想在渲染之前加載它。 我試過在渲染返回中添加一個<link>元素(沒有用),我也試過使用 vanilla JS 直接將標簽注入頭部,但這也不起作用:

async componentDidMount() {
    await this.fetchPanelInfo().then(result => {
        console.log(this.state);

        const link = document.createElement("link");
        link.href= this.state.stylePath;
        link.rel = "stylesheet";
        link.type="text/css";
        document.head.appendChild(link);
        //const style = document.getElementById("style-direction");
        //style.href = this.state.stylePath;
    })
}

縮短的組件:

class Panel extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        token: "f0be0f7d231305a832fd1eef4bcb0e9ba18f2d65",
        error: null,
        errmsg: null,

        menuContent: null,
        stylePath: null,
        services: null,

        loading: true
    }
    isLoggedIn().then(logged => {
        //Nothing for now
    })
}
//Gets all information about the panel
async fetchPanelInfo() {
    await axios({
        method: 'post',
        url: `${ENDPOINT}`,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        data: this.state
    }).then(result => {
        console.log(result.data);
        this.setState({
            error: result.data.error,
            menuContent: result.data.menu,
            stylePath: result.data.stylePath,
            services: result.data.services,
            loading: false
        });
    }).catch(err => {
        console.log("error");
        console.log(err);
        this.setState({error: err.error})
    });
}

async componentDidMount() {
    await this.fetchPanelInfo().then(result => {
        console.log(this.state);

        const link = document.createElement("link");
        link.href= this.state.stylePath;
        link.rel = "stylesheet";
        link.type="text/css";
        document.head.appendChild(link);
        //const style = document.getElementById("style-direction");
        //style.href = this.state.stylePath;
    })
}

render() {
    if(this.state.loading) return null;
    return (
        <section className="panel">

            <p>Hello</p>
            <Menu items={this.state.menuContent} />
        </section>
    );
}
}

這是一個<Router>導航到的頁面,所以我不能顯式地預取樣式表的名稱並單獨導入,因為加載的樣式表取決於提供的令牌(即,它因令牌而異)。

有任何想法嗎?

我設法加載並應用動態 .css 文件,如下所示:

async componentDidMount() {
    await this.fetchPanelInfo().then(result => {
        console.log(this.state);

        if(this.state.stylePath === undefined) {
            require("../" + "core/data/default/styles.css");
        } else {
            require("../" + this.state.stylePath);
        }
        const React = require('react');
    })
}

基本上使用require()模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM