1. 組件間數據通信的單向性
React組件之間的是彼此獨立的,組件間的數據流動是單向的,父組件向子組件通信是最常見的方法,父組件通過props
向子組件傳遞需要的信息。
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
const SubComp = ({myProp, myText}) => (
<span data-myProp={myProp}>{myText}</span>
);
const Page = ({pageProp, pageText}) => (
<SubComp myProp={pageProp} myText={`myText: ${pageText}`} />
);
ReactDOM.render(
<Page pageProp={1} pageText={'2'} />,
document.getElementById('page')
);
2. 子組件向父組件通信
在React中,子組件向父組件通信時,可以使用回調函數,或者自定義事件。
在簡單的場景中,回調函數常用的辦法。
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
const SubComp = ({myProp, myText, setParentState}) => (
<input type="button"
data-myProp={myProp}
onClick={() => setParentState({ text: +new Date })}
value={myText} />
);
class Page extends Component {
constructor(props) {
super(props);
this.state = {
text: 1
};
this.setParentState = this.setState.bind(this);
}
render() {
return (
<SubComp
myProp={this.props.pageProp}
myText={`myText: ${this.state.text}`}
setParentState={this.setParentState} />
);
}
}
ReactDOM.render(
<Page pageProp={1} pageText={'2'} />,
document.getElementById('page')
);
注:
(1)setState是一個異步方法,一個生命周期內所有的setState方法會合并操作。
在componentWillMount
中執行setState
方法,組件會更新state
,但是組件只渲染一次。
因此,這是無意義的執行,初始化時的state
,都可以放在this.state={...}
中。
(2)原生組件的自定義屬性應該加上'data-'前綴,React組件則不需要。
<span myProp={myProp}>{myText}</span>
Warning: Unknown prop `myProp` on <span> tag. Remove this prop from the element.