React兄弟元件之間的通信
Child2元件需要去更改Child1元件中的資料。
因為Child1和Child2是兄弟元件
是以資料和事件都放在最進的父級元件中去
兄弟元件通信的簡單使用
import React from 'react'; //這個是react這個包,我們是需要的
import ReactDOM from 'react-dom'; //這個是react的虛拟dom
class PartentHello extends React.Component {
state = {
num:10
}
// Child2中的元件事件的回調更改Child1中的資料
addHandler = () => {
this.setState({
num: this.state.num+10
})
}
render() {
return (
<div>
<Child1 num={ this.state.num}></Child1>
<Child2 addAdd={ this.addHandler}></Child2>
</div>
)
}
}
// 元件 Child1
const Child1 = props => {
return (
<h1>數量{props.num }</h1>
)
}
// 元件 Child2
const Child2 = props => {
return (
<button onClick={()=>props.addAdd()}>增加</button>
)
}
ReactDOM.render(<PartentHello></PartentHello>,document.getElementById('root'))
React中兄弟元件通信群組件跨級傳遞Context的使用 兄弟元件
将共享狀态提升到最近的公共父元件中。
由公共父元件來管理這個狀态(資料,事件)
它的思想就是狀态提升
元件跨級傳遞 Context
當Child1元件中有Child2元件。
Child2元件中有Child3元件。
Child3中有Child4元件
我們怎麼将Child1中的資料傳遞給Child4呢???
這個時候,我們就可以使用 Context.
他主要運用在資料跨元件傳遞。
如:背景顔色。 語言等
使用Context
import React from 'react'; //這個是react這個包,我們是需要的
import ReactDOM from 'react-dom'; //這個是react的虛拟dom
import './index.css'
// Provider是提供者, Consumer接受者
const { Provider, Consumer } = React.createContext()
class PartentHello extends React.Component {
render() {
return (
<Provider value='傳遞的資料'>
<div className='box'>
<Child1></Child1>
</div>
</Provider>
)
}
}
// 元件 Child1
const Child1 = () => {
return (
<div className='Child1'>
<h1> 我是Child1元件 </h1>
<Child2></Child2>
</div>
)
}
// 元件 Child2
const Child2 = () => {
return (
<div className='Child2'>
<h1> 我是Child2元件 </h1>
<Child3></Child3>
</div>
)
}
// 元件 Child3
const Child3 = () => {
return (
<div className='Child3'>
<h1> 我是Child3元件 </h1>
<Consumer>
{/* 千萬要注意 Consumer不能有其他内容,否者會報錯 */}
{data => <span>{data}</span>}
</Consumer>
</div>
)
}
ReactDOM.render(<PartentHello></PartentHello>,document.getElementById('root'))
總結 Context
使用Context的時候,他提供了兩個元件。
分别是 Provider, Consumer。
Provider元件是提供資料的。Consumer是接受資料的。
Provider是使用value進行傳遞。
Consumer通過下面這樣的方法進行接收資料
<Consumer>
{data => <span>{data}</span>}
</Consumer>
遇見問題,這是你成長的機會,如果你能夠解決,這就是收獲。