2017-11-25 85 views
1

我有一個組件,其中有一個複選框,並在複選框的Changed事件上,我想顯示一條消息,說它被檢查與否。 在VS Code中沒有錯誤,當我嘗試調試時,代碼在Changed事件上觸發並調用了tick函數並調用setstate,但是當我進入下一行時,它進入了一些內部的React JavaScript文件,發現很難理解,找出問題。目前我得到一個複選框,但選中或取消的消息不會改變反應檢查和取消選中CheckBox

import React,{ Component } from 'react'; 
class Checked extends Component{ 
constructor(props) 
{ 
    super(props);  
this.state= {check: true}; 


} 
tick() 
{ 
this.setState({check:!this.state.check}); 
    } 

    render(){ 
     var msg=""; 
     if (this.state.check=true) 
     { 
      msg="checked"; 
     } 
     else 
     { 
      msg="unchecked"; 
     } 
     return(<div><input type="checkbox" onChange={this.tick.bind(this)} defaultChecked={this.state.check} ></input> 
     <h1>checkbox is {msg}</h1> 
     </div>); 
    } 
} 

export default Checked; 
+1

'如果(this.state .check = true)'condition is wrong ... it must be'if(this.state.check == true)' – Jeevan

+0

它現在正在工作,謝謝Jeevan – krishna

回答

-1

您還可以在函數中添加邏輯,這個執行工作對我來說

import React from 'react'; 
import { render } from 'react-dom'; 


class Checked extends React.Component { 
    constructor(props) { 
    super(props); 

    this.tick = this.tick.bind(this); 


    this.state = { 
     checkBox: true, 
     checkedMsg: '' 
    } 
    } 

    tick() { 
    this.setState({ 
     checkBox: !this.state.checkBox 
    }) 

    this.state.checkBox ? this.setState({ checkedMsg: 'checked' }) : this.setState({ checkedMsg: 'unchecked' }) 

    } 

    render() { 
    return (
     <div> 
     <input 
      type="checkbox" 
      onClick={this.tick} 
      defaultChecked={this.state.check} 
     /> 
     <h1>checkbox is {this.state.checkedMsg}</h1> 
     </div> 
    ); 
    } 
} 

export default Checked; 

render(<Checked />, document.getElementById('root')); 
+0

您應該保持最小狀態。在這種情況下,checkedMsg不應該是另一個狀態,因爲它可以從state.check中計算出來。 –

+1

謝謝@Daniel Tran,你的權利我剛剛在React文檔 –

相關問題