2017-07-18 29 views
2

我已经有一个简单的切换组件反应,即时通讯相当不知道为什么它不会工作。另外,如果即时通讯使用箭头功能,我还需要绑定(这)?简单的开/关切换组件不工作

class MyComponent extends React.Component { 
    construtor(props){ 
    super(props); 
    this.state = {visibility: false}; 
    } 

    toggleVisibility =() => { 
    this.setState({ 
     visibility: !this.state.visibility 
    }); 
    } 

    render() { 
    if(this.state.visibility) { 
     return (
     <div> 
      <button 
      onClick={this.toggleVisibility}>Click</button> 
      <h1>now you see me</h1> 
     </div> 
    ); 
    } else { 
     return(
     <div> 
     <button 
     onClick={this.toggleVisibility}>Click</button> 
     </div> 
    ); 
    } 
    } 
}; 

ReactDOM.render(<MyComponent />, document.getElementById("root")); 
+0

当您提出问题时,请提供更多关于您遇到的问题的详细信息,而不是“不起作用”。错误消息,控制台日志等。它让我们有更多的需要。 – jered

+0

不要在'setState'中使用'this.state'。 https://facebook.github.io/react/docs/react-component.html#setstate – SLaks

+0

我正在写codepen,它给了我“toggle unexpectedness =”在toggleVisibility方法下,我猜是使用箭头函数 – Sotero

回答

0

我会做两个更改。首先,你不能像这样的箭头函数在你的组件上定义函数。这可能是因为它不工作。 (是的,这意味着你需要在你的构造函数中使用bind()这个函数。)其次,我会重构你的渲染器来有条件地显示你的<h1>标记,而不是整个组件。

class MyComponent extends React.Component { 
    constructor(props){ 
    super(props); 
    this.state = {visibility: false}; 
    this.toggleVisibility = this.toggleVisibility.bind(this); 
    } 

    toggleVisibility() { 
    this.setState({ 
     visibility: !this.state.visibility 
    }); 
    } 

    render() { 
     return (
     <div> 
      <button 
      onClick={this.toggleVisibility} 
      >Click</button> 
      {this.state.visibility ? <h1>now you see me</h1> : []} 
     </div> 
    ); 
    } 
}; 

ReactDOM.render(<MyComponent />, document.getElementById("root")); 

注意这部分:{this.state.visibility ? <h1>now you see me</h1> : []}。这是一个内联的三元条件。根据简单的布尔值,在JSX中显示或隐藏某些内容是一种非常常见的方式。使用花括号{}在JSX中嵌入表达式,其中三元条件将返回一个结果或另一个结果。 React不会像任何东西一样呈现像[]这样的空数组,因此当您不想呈现某个东西时,它便于使用。

三元运算符条件如下所示:someBoolean ? resultIfTrue : resultIfFalse

编辑:另外,constructor拼写错误,好抓@RyanHarvey。

1

您有一个错字。构造c tor,而不是construtor。

constructor(props){ 
    super(props); 
    this.state = {visibility: false}; 
} 

它工作正常,修正了这个错字。