React.js onClick事件:TypeError:无法读取undefined的属性

时间:2017-09-24 14:38:54

标签: reactjs event-handling undefined i18next uncaught-typeerror

目前很难学习React和JavaScript。

我有两个组件,导航

import React from 'react';
import ReactDOM from 'react-dom';
import Nav from './houses/Nav.js';

// set data
var navbar = {};
navbar.brand = {linkTo: "#hero", text: "text"};
navbar.links = [
      {linkTo: "#", event:"es", spanClassName: "flag-icon flag-icon-es"},
      {linkTo: "#", event:"en", spanClassName: "flag-icon flag-icon-gb"},
      {linkTo: "#about", text: "about", spanClassName: "btnicon icon-user"},
      {linkTo: "#contacts", text: "contacts", spanClassName: "btnicon icon-envelope-open"}
  ];

class Navigation extends React.Component {

  render() {
    return (
    <header>         
      <Nav {...navbar} />        
    </header>
    )
  }
}

module.exports = Navigation;

导航

import React from 'react';
import ReactDOM from 'react-dom';

class Nav extends React.Component {    

  render() {

    const changeLanguage = (lng) => {
      i18n.changeLanguage(lng);
    } 

      return(
        <nav className="navbar navbar-inverse navbar-fixed-top" role="navigation">
          <div className="container">
            <div className="navbar-header">
              <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="false">
                <span className="sr-only" lang="lt">Toggle nav</span> 
                <span className="icon-bar"></span>
                <span className="icon-bar"></span>
                <span className="icon-bar"></span>
              </button>
              <NavBrand linkTo={this.props.brand.linkTo} text={this.props.brand.text} />
            </div>
            <div className="collapse navbar-collapse">
              <NavMenu links={this.props.links} />
            </div>
          </div>
        </nav>
      );
    }
  };

  class NavBrand extends React.Component{
    render() {
      return (
        <a className="navbar-brand" alt="back to home" href={this.props.linkTo}>{this.props.text}
            <span className="brandicon"></span> 
            <span className="brandname"></span>   
        </a>
      ); 
    }
  };

  class NavMenu extends React.Component{
    render() {
      var links = this.props.links.map(function(link){       
          return (
            <NavLink linkTo={link.linkTo} text={link.text} active={link.active} event={link.event} spanClassName={link.spanClassName} />
          );

      });
      return (
        <ul className="nav navbar-nav navbar-right">
          {links}
        </ul>
      );
    }
  };

  class NavLink extends React.Component{
   render() {        

    if (this.props.event){
      return(
        <li><button onClick={() => changeLanguage(this.props.event)}>{this.props.event}<span className={(this.props.spanClassName)}></span></button></li>
      )
    }
    return(        
      <li className={(this.props.active ? "active" : "")}><a href={this.props.linkTo}>{this.props.text} <span className={(this.props.spanClassName)}></span></a></li>
    );
  }
};


  module.exports = Nav;

目前,我想将自定义onClick事件仅添加到具有language属性的某个<li>元素。它应该渲染:

在其他组件的render()中使用onClick事件如下所示:        onClick={() => changeLanguage('lang_attribute')} 所以我应该通过导航渲染得到相同的结果

按下渲染按钮我收到错误消息:Uncaught TypeError: Cannot read property 'changeLanguage' of undefined

需要一些有关工作样本的帮助

更新 似乎我的问题主要与18下一个相关。我正在研究i18n文件(另外我必须对菜单项进行翻译)并做了一些尝试,但据我所知,问题在于HOC和i18n功能。它们超出了范围,因为这里有几个类。 所以我得到两个错误:t不是函数,而i18n是未定义的。

import React from 'react';
import ReactDOM from 'react-dom';
import {translate} from 'react-i18next';


class Nav extends React.Component {

  render() {

      return(
        <nav className="navbar navbar-inverse navbar-fixed-top" role="navigation">
          <div className="container">
            <div className="navbar-header">
              <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="false">
                <span className="sr-only">Toggle</span> 
                <span className="icon-bar"></span>
                <span className="icon-bar"></span>
                <span className="icon-bar"></span>
              </button>              
              <NavBrand linkTo={this.props.brand.linkTo} text={this.props.brand.text} />
            </div>
            <div className="collapse navbar-collapse">
              <NavMenu links={this.props.links} />
            </div>
          </div>
        </nav>
      );
    }
  };

  class NavBrand extends React.Component{
    render() {

      return (
        <a className="navbar-brand" alt="back to home" href={this.props.linkTo}>{this.props.text}
            <span className="brandicon"></span> 
            <span className="brandname"></span>   
        </a>
      ); 
    }
  };

  class NavMenu extends React.Component{
    render() {

      const { t, i18n } = this.props;

      var links = this.props.links.map(function(link, index){         
          return (
            <PureNavLink  linkTo={link.linkTo} text={t(link.text)} active={link.active} event={link.event} spanClassName={link.spanClassName} />
            /*text={t(link.text)}*/  

          );

      });
      return (
        <ul className="nav navbar-nav navbar-right">
          {links}
        </ul>
      );
    }
  };

  class PureNavLink  extends React.Component{

    render() {        
      const { t, i18n } = this.props;
      const toggle = lng => i18n.changeLanguage(lng);       

      if (this.props.event){        

        return(  
          <div>               

          <button onClick={() => toggle(this.props.event)}>{t(this.props.event)}</button>          
          </div>        
        )
      }

      return(        
        <li className={(this.props.active ? "active" : "")}><a href={this.props.linkTo}>{this.props.text} <span className={(this.props.spanClassName)}></span></a></li>        
      );
    }
  };

  const NavLink = translate()(PureNavLink);
  module.exports = translate()(Nav);

2 个答案:

答案 0 :(得分:2)

因此,您似乎在changeLanguage方法中为render()定义了Nav函数。因此,changeLanguage绑定到Nav的范围和上下文,因此您的NavLink组件对此一无所知。首先尝试将changeLanguage移出任何组件,然后查看它是否被调用,即

// define the function outside of component scope
const changeLanguage = (lng) => {
  i18n.changeLanguage(lng);
};

// function is now available for use in any component in
// this module - just export it to use it in other modules
class Nav extends React.Component {

  render() {
    // your code and other components
  }
}

React组件中定义的方法和函数绑定到该组件的实例。在其他地方调用该函数或方法的唯一方法是:1)在任何组件之外定义该函数,或者2)将对函数或方法的引用作为prop传递给子组件。如果执行2号操作,请务必绑定原始组件的this上下文,否则会出现类似于您所看到的错误。

答案 1 :(得分:1)

帕克的答案是正确的

a)像上面的代码一样移动changeLanguage - 但也是import i18n from '../i18n';或你定义你的i18n实例的地方。

import i18n from 'i18n';

// define the function outside of component scope
const changeLanguage = (lng) => {
  i18n.changeLanguage(lng);
};

// function is now available for use in any component in
// this module - just export it to use it in other modules
class Nav extends React.Component {

  render() {
    // your code and other components
  }
}

或者b)通过道具传递changeLanguage。

// ...
<NavMenu links={this.props.links} changeLanguage={changeLanguage} />

// ...
<NavLink changeLanguage={changeLanguage} linkTo={link.linkTo} text={link.text} active={link.active} event={link.event} spanClassName={link.spanClassName} />

或者c)使用translate hoc

装饰您的NavLink
class PureNavLink extends React.Component{

    render() {        
      const { t, i18n } = this.props;
      const toggle = lng => i18n.changeLanguage(lng); 

      if (this.props.event){        

        return(  
          <div>               

          <button onClick={() => toggle(this.props.event)}>{t(this.props.event)}</button>
          </div>        
        )
      }

      return(        
        <li className={(this.props.active ? "active" : "")}><a href={this.props.linkTo}>{this.props.text} <span className={(this.props.spanClassName)}></span></a></li>        
      );
    }
  };

const NavLink = translate()(PureNavLink);

https://react.i18next.com/components/translate-hoc.html

或者d)使用渲染道具I18n https://react.i18next.com/components/i18n-render-prop.html