反应|多个上下文|无法使用默认值

时间:2018-08-02 12:04:30

标签: javascript reactjs

我正在尝试在React 16.4中发布的新上下文API。我在使用多个上下文时陷入困境,无法使用Providers的默认值,但是在Single Contexts的情况下,消费者能够接收Providers的默认值。

上下文:

const btnToggleContent = document.getElementsByClassName("toggleContent");

var toggleContent = function(e) {

/*e.target will get the clicked element which is the button clicked and parentElement 
gives you the parent element of this button which is the card you want to modify*/
    var card = e.target.parentElement;
    
/*when you have the card you can use on its getElementsByClassName to retreive all 
elements that have the class (cardMoreContent) in this case theres only one so you take
the first element from the array returned with [0]*/
    var cardMoreContent = card.getElementsByClassName("cardMoreContent")[0];
    
    //then rest of the code stays the same
    cardMoreContent.classList.toggle("showing");

    if(this.classList.contains("toggledOff")) {
      this.innerHTML = "More";
    }
    else {
      this.innerHTML = "Less";
    }
}



for (var i = 0; i < btnToggleContent.length; i++) {
  btnToggleContent[i].addEventListener("click", toggleContent);
}

提供商

const ThemeContext = React.createContext("light");
const UserContext = React.createContext({ name: "Guest" });`

消费者

 <ThemeContext.Provider>
        <UserContext.Provider>
          <Main />
        </UserContext.Provider>
      </ThemeContext.Provider>

请找到沙盒链接:https://codesandbox.io/s/6w8qn7yy4k

谢谢。

2 个答案:

答案 0 :(得分:3)

根据React文档:

  

defaultValue仅在Consumer时使用   树上没有匹配的Provider

// context
const ThemeContext = React.createContext("light");
const UserContext = React.createContext({ name: "Guest" });

function Content() {
  return (
    <ThemeContext.Consumer>
      {theme => <ProfilePage theme={theme} />}
    </ThemeContext.Consumer>
  );
}


class App extends React.Component {
  render() {
    return (
      <UserContext.Provider>
        <Main />
      </UserContext.Provider>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

上面的代码没有提供ThemeContext的提供程序,因此它采用默认值。

如果您同时使用这两个提供程序,则需要向所有提供程序提供价值,例如

<ThemeContext.Provider value={"light"}>
    <UserContext.Provider value={{ name: "Guest" }}>
      <Main />
    </UserContext.Provider>
 </ThemeContext.Provider>

答案 1 :(得分:0)

只有在渲染树中没有匹配的createContext()组件时,<Provider/>调用中传递的默认值才会提供给使用者。

在CodeSandBox示例中,您的<App />组件同时渲染了两个<Provider />组件,但未传递value道具,这导致了不确定的值。

我将您的CodeSandBox更新为仅呈现<Content />组件。注意默认值现在如何工作:) https://codesandbox.io/s/j207ollx89