React的狀態提升就是用戶對子組件操作,子組件不改變自己的狀態,通過自己的props把這個操作改變的數據傳遞給父組件,改變父組件的狀態,從而改變受父組件控制的所有子組件的狀態,這也是React單項數據流的特性決定的。官方的原話是:共享 state(狀態) 是通過將其移動到需要它的組件的最接近的共同祖先組件來實現的。 這被稱為“狀態提升(Lifting State Up)”。
現在有個需求,有兩個輸入框,分別用來輸入美元和人民幣的數額,要求不管用戶輸入美元還是人民幣,另一個輸入框顯示出根據匯率計算出的對應的數額。
每個組件的state是自己特有的,不能傳遞給其他組件,其他組件也無法更改。但是我們可以把input中值的顯示控制權交給input的父組件,即把用戶輸入的數值通過props傳遞給它的父親組件,在更新父組件的狀態后,把這個值再傳遞給input,做個顯示就可以了。
class Dollar extends React.Component{ constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.props.dollarChange(event.target.value); //將子組件的值通過props傳給父組件 } render() { const money = this.props.money; const yuan = this.props.yuan; const text = this.props.type == 'd' ? '美元' : '人民幣'; return <fieldset> <legend>{text}</legend> <input value={money} onChange={this.handleChange}/> </fieldset> } } class Box extends React.Component{ constructor(props){ super(props); this.state = { dollar: '', yuan: '', }; this.dollarInput = this.dollarInput.bind(this); this.yuanInput = this.yuanInput.bind(this); } dollarInput(value) { if (parseFloat(value) || value == '' || parseFloat(value) == 0) { this.setState({ dollar: value, yuan: value == '' ? '' : value * 6.7951 }); } else { alert('輸入值必須為數字。'); } } yuanInput(value) { if (parseFloat(value) || value == '' || parseFloat(value) == 0) { this.setState({ dollar: value == '' ? '' : value * 0.1472, yuan: value, }); } else { alert('輸入值必須為數字。'); } } render() { return <div> <Dollar type = {'d'} dollarChange = {this.dollarInput} money = {this.state.dollar}/> <Dollar type = {'y'} dollarChange = {this.yuanInput} money = {this.state.yuan}/> </div> } } ReactDOM.render( <Box />, document.getElementById('main') );
官方文檔參考地址:http://www.css88.com/react/docs/lifting-state-up.html