適用於剛開始接觸react直接上手的同學,建議還是打好JS和ES6基礎。
基礎
父傳子
子傳父
兄弟組件傳遞
進階(待完成)
不太相關組件之間傳遞
redux
ref
context
observer pattern
全局變量
基礎內容
(1)父傳子:可以通過props將父組件數據傳給子組件
function Parent(){
return (
<Child name = "child1"/>
)
}
function Child(props){
return <button >{props.name}</button>
}
ReactDOM.render(<Parent />, document.getElementById("root"));
如上所示,
上面這段的props為{name:"child"}如果不太明白props的話可以看下面這段。
、
(2)子傳父:可以通過繼承父組件的函數來改變父組件的狀態。(回調函數,事件)
也需要父組件向子組件傳遞 props 進行通訊,只是父組件傳遞的,是作用域為父組件自身的函數,子組件調用該函數,將子組件想要傳遞的信息,作為參數,傳遞到父組件的作用域中。
有兩種傳遞方式:
方法一:直接調用父組件的方法
方法二: 先調用自身的方法,再調用父組件的方法
class Parent1 extends React.Component{
constructor(props){
super(props);
this.state ={
msg:'父類消息',
}
}
onButtonClick = (msg) => {
this.setState({msg: '子類信息'})
}
render(){
return (
<div>
<p> 子傳給我的信息:{this.state.msg}</p>
{/*方法一調用方式*/}
<Child1 name = "child1" onClick ={this.onButtonClick}/>
{/*方法二調用方式 */}
<Child2 name = "child1" onButtonClick ={this.onButtonClick}/>
</div>
)
}
}
// 方法一:直接調用父組件的方法
function Child1(props){
return <button onClick={props.onClick}>{props.name}</button>
}
//方法二:先調用自身的方法,再調用父組件的方法
function Child2(props){
childClickHandle = (msg) =>{
this.props.onButtonClick(msg); //這個onButtonClick對應 <Child2 name = "child1" onButtonClick = //{this.onButtonClick}/>中第一個onButtonClick
}
return <button onClick={childClickHandle}>{props.name}</button>
}
ReactDOM.render(<Parent1 />, document.getElementById("root"));
(3)兄弟組件傳值(子傳給父,父再傳給另一個子),一般來説,兩個非父子組件想要通信,首先我們可以看看它們是否是兄弟組件,即它們是否在同一個父組件下。如果不是的話,考慮下用一個組件把它們包裹起來從而變成兄弟組件是否合適。這樣一來,它們就可以通過父組件作為中間層來實現數據互通了。
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {count: 0}
}
setCount = () => {
this.setState({count: this.state.count + 1})
}
render() {
return (
<div>
<SiblingA
count={this.state.count}
/>
<SiblingB
onClick={this.setCount}
/>
</div>
);
}
}
const SiblingA = (props) => {
return <button>{props.count}</button>
}
const SiblingB = (props) => {
return <button onClick={props.onClick}>button2</button>
}
ReactDOM.render(
<Parent/>,
document.getElementById('root')
);