在 React 16.4.0 中,为什么要使用内置的 Context 组件,当你可以使用类似对象字面量的东西来完成同样的事情时,你可以导入给任何需要它的人?
在 Facebook 的示例 ( https://reactjs.org/docs/context.html#examples ) 中,theme-context.js 文件可以直接传递对象文字而不是使用 ThemeContext。 app.js 代码可以读取主题上下文导出的对象文字并将其值作为 Prop 传递给 them-button.js。使用上下文组件似乎是不必要的。这是取自 Facebook's tutorial 的代码:
主题上下文.js
export const themes = {
light: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
};
export const ThemeContext = React.createContext(
themes.dark // default value
);
主题按钮.js
import {ThemeContext} from './theme-context';
function ThemedButton(props) {
return (
<ThemeContext.Consumer>
{theme => (
<button
{...props}
style={{backgroundColor: theme.background}}
/>
)}
</ThemeContext.Consumer>
);
}
export default ThemedButton;
应用程序.js
import {ThemeContext, themes} from './theme-context';
import ThemedButton from './themed-button';
// An intermediate component that uses the ThemedButton
function Toolbar(props) {
return (
<ThemedButton onClick={props.changeTheme}>
Change Theme
</ThemedButton>
);
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
theme: themes.light,
};
this.toggleTheme = () => {
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
};
}
render() {
// The ThemedButton button inside the ThemeProvider
// uses the theme from state while the one outside uses
// the default dark theme
return (
<Page>
<ThemeContext.Provider value={this.state.theme}>
<Toolbar changeTheme={this.toggleTheme} />
</ThemeContext.Provider>
<Section>
<ThemedButton />
</Section>
</Page>
);
}
}
ReactDOM.render(<App />, document.root);
最佳答案
您错过的一件事是,上下文的更改将通过启动重新渲染来影响消费者那里接收到的值,这无法通过导入值来实现。
关于javascript - 在 React 16.4.0 中,使用新的上下文语法比仅导出对象字面量有何优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50828834/