簡體   English   中英

react從ReactDOM.render調用一個函數

[英]react call a function from ReactDOM.render

在我的index.js文件中,我有這個:

const store = createStore(
    combineReducers({
        i18n: i18nReducer
    }),
    applyMiddleware(thunk)
);
syncTranslationWithStore(store)
store.dispatch(loadTranslations(translationsObject));
store.dispatch(setLocale('de'));

使用此代碼,默認語言設置為greman。 現在,我想在ReactDOM.render中創建一個Button,最多可以用stahet(de / en)來更改語言。

我所做的是這樣的:

function changeLanguage() {
    function handleClick(e) {
        e.preventDefault();
        store.dispatch(setLocale('de'));
    }
}

和在ReactDOM中

 <Router history={hashHistory}>
        <div>
            <div className="sidebararound">
                <div className="sidebar">
                    <ul>
                        <li><a className="fa fa-language fa-2x" onClick={this.changeLanguage.handleClick.bind()} aria-hidden="true"></a></li>

但是那是行不通的。 我有一張白紙。 我的錯誤在哪里?

謝謝

在構造函數中綁定事件始終是一個好習慣。

constructor(props) {
   super(props);
   this.handleClick = this.handleClick.bind(this)
   ....
}

handleClick(e){
  e.preventDefault();
  store.dispatch(setLocale('de'));
}

並在render方法中:

<Router history={hashHistory}>
        <div>
            <div className="sidebararound">
                <div className="sidebar">
                    <ul>
                        <li><a className="fa fa-language fa-2x" onClick={this.handleClick} aria-hidden="true"></a></li>

暫無
暫無

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

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