从子组件reactjs运行函数

时间:2018-03-06 13:35:14

标签: javascript reactjs

Layout.js文件是 hoc ,如下所示:

import React, { Component } from 'react';
import { I18n } from 'react-i18next';

class Layout extends Component {
.
.
.
render() {
  return (
    <I18n ns="translations">
      {(t, { i18n }) => (
        <Aux>
          <Toolbar
            blablabla
          />
          <SideDrawer
            blablabla
          />
          <main className={classes.Content}>{this.props.children}
          </main>
        </Aux>
       )}
     </I18n>
    );
  }
}

export default Layout;

Toolbar.js是一个像这样的无状态组件:

import React from 'react';
import NavigationItems from '../NavigationItems/NavigationItems';
.
.
const toolbar = props => {
  <nav className={classes.DesktopOnly}>
    <NavigationItems isAuthenticated={props.isAuth} />
  </nav>
}
export default toolbar;

NavigationItems.js是这样的:

import React from 'react';
import NavigationItemMenu from './NavigationItemMenu/NavigationItemMenu';
import i18n from '../../../i18n';

const navigationItems = props => (
 <ul className={classes.NavigationItems}>
    <NavigationItemMenu>
      {i18n.t('Navigation.NavigationItems.NavigationItems.languaje')}
    </NavigationItemMenu>
 </ul>
);
export default navigationItems;

最终NavigationItemMenu.js是这样的:

import React, { Component } from 'react';
import i18n from '../../../../i18n';
.
.
class NavigationItemMenu extends Component {
 .
 .
 .
 render() {
   return (
     <MenuList role="menu">
       <MenuItem onClick={this.handleClose('en')}>    
         {i18n.t('Navigation.NavigationItems.NavigationItems.en')}
       </MenuItem>
     </MenuList>
   )
  }
}
export default NavigationItemMenu;

问题是:如果我运行此代码:

<button onClick={() => i18n.changeLanguage('en')}>en</button>
layout.js中的

就像魅力一样。您可以在此链接中查看示例:

https://github.com/i18next/react-i18next/blob/master/example/react_renderProps/src/App.js

但是,如果我尝试在最后一个文件NavigationItemMenu.js中运行此代码,请执行以下操作:

<MenuItem
  onClick={(this.handleClose, () => i18n.changeLanguage('en'))           
  {i18n.t('Navigation.NavigationItems.NavigationItems.en')}
</MenuItem>

不起作用。 langiaje没有改变,错误在哪里?

的Pd。对不起,我是新手,反应!

非常感谢!

1 个答案:

答案 0 :(得分:1)

onClick语法看起来很奇怪。

尝试

<MenuItem
  onClick={() => {
      this.handleClose();
      i18n.changeLanguage('en')
  }}           
/>
  {i18n.t('Navigation.NavigationItems.NavigationItems.en')}
</MenuItem>