在react中,父子組件可以通過props來傳遞消息。而在實際開發中經常會遇到幾個組件需要共享數據的情況,react提供的一種方法就是將他們共享的狀態提升至離他們最近的父組件中進行統一管理。這種機制稱爲“狀態提升”。
這裏用一個例子來具體說明。假設我們有兩個輸入框,在其中任何一個輸入框中輸入內容,另一個框中的內容也會隨着改變。每個輸入框都是一個組件,這就涉及到組件之間的信息傳遞。因此我們創建一個狀態管理組件作爲這兩個輸入組件的父組件來統一管理狀態。 body部分的代碼如下:
<body>
<div id="root"></div>
<script type="text/babel">
class InputBox extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.inputChange(e.target.value);
}
render() {
const input= this.props.input;
return (<form>
<label for="input">input something:</label>
<input id="input" value={input} onChange={this.handleChange}/>
</form>
);
}
}
class Control extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(input) {
this.setState({input: input});
}
render() {
return (
<div>
<InputBox inputChange={this.handleChange} input={this.state.input}/>
<InputBox inputChange={this.handleChange} input={this.state.input}/>
</div>
)
}
}
ReactDOM.render(
<Control/>,
document.getElementById('root')
)
</script>
</body>
由以上代碼可以看到,InputBox組件中,當輸入發生變化時,綁定的onChange事件是一個從父組件傳遞過來的函數。而這個函數的具體執行位置在父組件中,同時在父組件中改變了input狀態,然後再傳遞給子組件。使得各子組件重新渲染。以此實現了兄弟節點的消息傳遞。