React 之React.createContext
<p>使用<code>Context</code>,可以跨越组件进行数据传递</p><p> </p>
<div class="cnblogs_code">
<pre>import React from 'react'<span style="color: rgba(0, 0, 0, 1)">;
import ReactDOM from </span>'react-dom'<span style="color: rgba(0, 0, 0, 1)">;
const ThemeContext </span>=<span style="color: rgba(0, 0, 0, 1)"> React.createContext({
background: </span>'red'<span style="color: rgba(0, 0, 0, 1)">,
color: </span>'white'<span style="color: rgba(0, 0, 0, 1)">
});</span></pre>
</div>
<p> </p>
<p>通过静态方法<code>React.createContext()</code>创建一个<code>Context</code>对象,这个<code>Context</code>对象包含两个组件,<code><Provider /></code>和<code><Consumer /></code>。</p>
<p> </p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 0, 1)">class App extends React.Component {
render () {
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> (
</span><ThemeContext.Provider value={{background: 'green', color: 'white'}}>
<Header />
</ThemeContext.Provider>
<span style="color: rgba(0, 0, 0, 1)"> );
}
}</span></pre>
</div>
<p><code><Provider /></code>的<code>value</code>相当于现在的<code>getChildContext()</code>。</p>
<p> </p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 0, 1)">class Header extends React.Component {
render () {
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> (
</span><Title>Hello React Context API</Title>
<span style="color: rgba(0, 0, 0, 1)"> );
}
}
class Title extends React.Component {
render () {
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> (
</span><ThemeContext.Consumer><span style="color: rgba(0, 0, 0, 1)">
{context </span>=><span style="color: rgba(0, 0, 0, 1)"> (
</span><h1 style={{background: context.background, color: context.color}}><span style="color: rgba(0, 0, 0, 1)">
{</span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.props.children}
</span></h1>
<span style="color: rgba(0, 0, 0, 1)"> )}
</span></ThemeContext.Consumer>
<span style="color: rgba(0, 0, 0, 1)"> );
}
}</span></pre>
</div>
<p><code><Consumer /></code>的<code>children</code>必须是一个函数,通过函数的参数获取<code><Provider /></code>提供的<code>Context</code></p>
<p> </p>
<p><span style="color: rgba(255, 0, 0, 1)">参考自:https://www.jianshu.com/p/eba2b76b290b</span></p>
<p> </p>
</div>
<div id="MySignature" role="contentinfo">
此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935.
我的gitHub: (学习代码都在gitHub)
https://github.com/nwgdegitHub/<br><br>
来源:https://www.cnblogs.com/liuw-flexi/p/11652688.html
頁:
[1]