2016-04-21 50 views
0

單擊第二個單選按鈕可更改觸發呈現事件的狀態。但是,即使state.type已更改,它也會再次將第一個單選按鈕呈現爲已選中的單選按鈕。基於狀態的reactjs無線電組設置檢查屬性

var MyComponent = React.createClass({ 
 
    getInitialState: function() { 
 
    return { 
 
     type: 1 
 
    }; 
 
    }, 
 
    render: function() { 
 
    console.log('->> type: ' + this.state.type);//prints the expected value 
 
    return (<div className="my-component"> 
 
     <label>type 1</label> 
 
     <input ref="type1Selector" type="radio" name="type" id="type1" 
 
     onChange={this.changeHandler} checked={this.state.type === 1}/><br/> 
 
     <label>type 2</label> 
 
     <input ref="type2Selector" type="radio" name="type" id="type2" 
 
     onChange={this.changeHandler} checked={this.state.type === 2}/><br/> 
 
    </div>); 
 
    }, 
 
    changeHandler: function(e) { 
 
    e.preventDefault(); 
 
    var t = e.currentTarget; 
 
    if(t.id === 'type1') { 
 
     this.setState({type: 1}); 
 
    } else { 
 
     this.setState({type: 2}); 
 
    } 
 
    } 
 
}); 
 
ReactDOM.render(<MyComponent />, document.getElementById('container'));
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-with-addons.min.js"></script> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.min.js"></script> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body> 
 
    <div id="container"></div> 
 
</body> 
 
</html>

有人可以告訴你怎麼得到這個工作,爲什麼REACT爲表現這樣嗎?

回答

0

正如在React文檔here中所述,複選框和單選按鈕可能存在問題。

請注意,爲了規範化複選框和廣播輸入的更改處理,React使用click事件代替更改事件。除非在更改處理程序中調用preventDefault,否則大多數情況下的行爲與預期相同。 preventDefault停止瀏覽器直觀地更新輸入,即使選中了切換。這可以通過去除對preventDefault的調用或將選中的切換置於setTimeout中來解決。

所以你想要做的就是刪除changeHandler函數中的e.preventDefault()