述律 發表於 2019-10-11 10:40:00

React 之React.createContext

<p>使用<code>Context</code>,可以跨越组件进行数据传递</p>
<p>&nbsp;</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>&nbsp;</p>
<p>通过静态方法<code>React.createContext()</code>创建一个<code>Context</code>对象,这个<code>Context</code>对象包含两个组件,<code>&lt;Provider /&gt;</code>和<code>&lt;Consumer /&gt;</code>。</p>
<p>&nbsp;</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>&lt;ThemeContext.Provider value={{background: 'green', color: 'white'}}&gt;
      &lt;Header /&gt;
      &lt;/ThemeContext.Provider&gt;
<span style="color: rgba(0, 0, 0, 1)">    );
}
}</span></pre>
</div>
<p><code>&lt;Provider /&gt;</code>的<code>value</code>相当于现在的<code>getChildContext()</code>。</p>
<p>&nbsp;</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>&lt;Title&gt;Hello React Context API&lt;/Title&gt;
<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>&lt;ThemeContext.Consumer&gt;<span style="color: rgba(0, 0, 0, 1)">
      {context </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> (
          </span>&lt;h1 style={{background: context.background, color: context.color}}&gt;<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>&lt;/h1&gt;
<span style="color: rgba(0, 0, 0, 1)">      )}
      </span>&lt;/ThemeContext.Consumer&gt;
<span style="color: rgba(0, 0, 0, 1)">    );
}
}</span></pre>
</div>
<p><code>&lt;Consumer /&gt;</code>的<code>children</code>必须是一个函数,通过函数的参数获取<code>&lt;Provider /&gt;</code>提供的<code>Context</code></p>
<p>&nbsp;</p>
<p><span style="color: rgba(255, 0, 0, 1)">参考自:https://www.jianshu.com/p/eba2b76b290b</span></p>
<p>&nbsp;</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]
查看完整版本: React 之React.createContext