处理React onToggle事件时遇到问题

时间:2018-10-17 04:09:09

标签: reactjs

能否请您看一下此代码段,并让我知道为什么我无法将onToggle事件与按钮组件绑定。我在编译时未定义“ onToggle”

在我的主容器(内容)中

class Content extends Component {
  constructor() {
    super();
    this.state = {
      user: dataService.User
    }
  }
  onTogglePane(){
    var node = ReactDOM.findDOMNode(this.refs.wrapper);
    node.classList.toggle('toggled');
  }
onSignOut() {
dataService.Logout((result) => {
  this.setState({
    user: null
  })
});
}
render() {
return (
  <div>
    <Header 
      onClick = {this.onSignOut}
      onToggle ={this.onTogglePane}
    />

  </div>
 )
 }
}

在Button.js中,我的按钮组件为

import React from 'react';

const Button = ({ text, styleClass, onClick }) => {
  return (
    <button
      type="button"
      onClick={e => onClick(e)}
     onToggle={e => onToggle(e)}
      className={`btn ${styleClass}`}
    >
      {text}
    </button>
  );
};

export default Button;

最后在我拥有的Header.js中

import React from 'react';
import Button from 'components/Button';
class Header extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <nav className="navbar navbar-default hk-navbar fixed-top">
        <p className="navbar-brand tk-brand">App</p>
        <Button
          text={[<i class="icon icon-logout"></i>,  " Sign Out"]}
          onClick = {(e) => this.props.onClick(e)}
          styleClass = 'btn-control'
        />
          <Button
          text={[<i class="icon icon-logout"></i>,  " Full Screen"]}
          onToggle = {(e) => this.props.onToggle(e)}
          styleClass = 'btn-control'
        />
      </nav>
    );
  }
}

export default Header;

现在我收到此错误

Failed to compile
./src/components/Button.js
  Line 8:  'onToggle' is not defined  no-undef

Search for the keywords to learn more about each error.

1 个答案:

答案 0 :(得分:1)

尝试一下,您缺少将其传递给Button组件的onToggle。

下面的Button组件代码将解决此问题

 import React from 'react';

 const Button = ({ text, styleClass, onClick, onToggle }) =>    {
    return (
       <button
        type="button"
       onClick={onClick ? onClick: null}
       onToggle={onToggle ? onToggle: null}
       className={`btn ${styleClass}`}
      >
        {text}
     </button>
     );
  };

  export default Button;