2016-06-13 52 views
0

中沒有保留狀態,當我點擊標籤面板中的複選框時,就會按照期望進行檢查。但是,當我切換到另一個面板,然後切換回來,我發現應該檢查的複選框轉到未選中狀態。我該如何解決?複選框在React

這是我的代碼,我使用npm的react-tab-panel

Container:

export default class Container extends Component { 
    static propTypes = { 
    }; 
    constructor(props) { 
     super(props); 
     this.state = { 
      chosenItem: { 
       a: [], 
       b: [], 
       c: [], 
       d: [] 
      } 
     }; 
    } 

    handleCheckBoxChange = (e) => { 
     const value = e.target.value; 
     const item = e.target.attributes.getNamedItem('data-tag').value; 
     const chosenItem = this.state.chosenItem; 
     const index = chosenItem[item].indexOf(value); 
     if (index > -1) { 
      chosenItem[item].splice(index, 1); 

     } 
     chosenItem[item].push(value); 

    } 

    render() { 
     return (
      <div> 
       <Panel 
        handleCheckBoxChange={this.handleCheckBoxChange} 

       /> 
      </div> 
     ); 
    } 
} 

Panel:

import TabPanel from 'react-tab-panel'; 
import 'react-tab-panel/index.css'; 
import CheckBox from './CheckBox.jsx'; 

export default function Panel({ 

    handleCheckBoxChange 
}) { 
    const tabList = { 
     a: ['1', '2'], 
     b: ['1', '2'], 
     c: ['1', '2'], 
     d: ['1', '2'] 
    }; 

    return (
     <TabPanel 
      tabPosition="left" 
     > 
     { 
      Object.keys(tabList).map((key) => { 
       return (
        <form 
         key={key} 
         tabTitle={key} 
        > 
        { 
         tabList[key].map((item) => 
          <CheckBox 
           key={item} 
           value={item} 
           handleCheckBoxChange={handleCheckBoxChange} 
           tag={key} 
          /> 
         ) 
        } 
        </form> 
       ); 
      }) 
      } 
     } 
     </TabPanel> 
    ); 
} 

Checkbox:

export default function CheckBox({ 
    tag, 
    value, 

    handleCheckBoxChange 
}) { 
    return (
     <div> 
      <label> 
       <input 
        type="checkbox" 
        value={value} 

        onChange={handleCheckBoxChange} 
        data-tag={tag} 
       /> 
       {value} 
      </label> 
     </div> 
    ); 
} 
+0

您應該使用['setState'](https://facebook.github.io/react/docs/component-api.html#setstate)更改組件的狀態。 – robertklep

+0

@robertklep setState在我的情況下不是一個好的解決方案。因爲我也使用react-router,所以如果我改變路徑然後回到這個路徑,所有的狀態都會消失。 – Downpooooour

回答

1

您應該考慮使用FluxRedux用於存儲應用程序狀態樹。

+0

我只是使用了REDX。我已經用redux修復了它。不管怎樣,謝謝。 – Downpooooour