摘要:提供了除之外的传参数的方式。是全局跨组件传递数据的。在线示例推荐阅读手稿
Context
Context提供了除props之外的传参数的方式。
Context是全局跨组件传递数据的。
API
React.createContext
const {Provider, Consumer} = React.createContext(defaultValue);
Provider
Consumer
Example ThemeContext.js{value => /* render something based on the context value */}
import React from "react";
export const themes = {
light: {
foreground: "#000000",
background: "#eeeeee",
},
dark: {
foreground: "#ffffff",
background: "#222222",
},
};
export default React.createContext(
themes.dark // default value
);
ThemedButton.jsx
import React from "react";
import ThemeContext, {themes} from "./ThemeContext";
export default ({children}) => {
const styles = {
color: themes[theme].foreground,
backgroundColor: themes[theme].background
};
return (
{theme => {
return (
)
}}
);
}
App.js
import React, {PureComponent} from "react";
import ThemeContext from "./ThemeContext";
import ThemeButton from "./ThemedButton";
export default class extends PureComponent {
constructor(props) {
super(props);
this.state = {theme: "dark"};
}
render() {
return (
{
this.setState({theme: this.state.theme === "dark" ? "light" : "dark"})
}}>Themed Button
);
}
}
在线示例
推荐阅读《React 手稿》
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/108715.html
摘要:官方也陈述,接下来的的工作会投入到中。从目前官方的文档可以看出,从以下四个方面来提高的编码。生命周期自定义方法的主要用途是替代之前版本的组件。说明到目前为止,在已发布的版本中有该功能,想体验该功能,必须安装。 React Hooks React在16.7.0-alpha.0版本中提到了Hooks的概念,目前还是Proposal阶段。 官方也陈述,接下来的90%的工作会投入到React ...
摘要:属性是必须的。需要一个与的一致。必须在的返回原。调试插件日志安装组件。然后加入到中即可例如扩展程序需要在应用市场安装然后在中使用增强功能将加入即可在线实例推荐阅读手稿 React-Redux Redux Action function addTodo(text) { return { type: ADD_TODO, text } } type 属性是必须的。...
摘要:实例在线实例定义写在函数中,是一个对象。一般情况下需要指定默认值,预防抛使用在组件中通过访问组件对象属性的方式。把这种组件也称为非受控性组件。通过提供了方法,来实现的修改。回调非控组件在线实例受控组件在线实例推荐阅读手稿 Component state 实例: import React, { PureComponent } from react; export default cla...
摘要:相当于一个放置在与中的垫片。之所以称之谓副作用呢,就是为了不让触发一个时,立即执行。也就是在与之间做一个事情,比如异步获取数据等。使用了中的功能,避免了像的回调地狱。把放入中最后再实现相就的即可在线示例推荐阅读手稿 Redux-Saga redux-saga 是一个用于管理应用程序副作用(例如异步获取数据,访问浏览器缓存等)的javascript库,它的目标是让副作用管理更容易,执行更...
摘要:类型检查是为了确保传入组件的参数正确性。通常在项目中可以使用或者来实现。示例以上内容在实现一个通用组件时非常有用。类型检查和参数默认值一起使用,保证组件的正常运行。 Typechecking With PropTypes 类型检查是为了确保传入组件的参数正确性。 通常在项目中可以使用Flow或者TypeScript来实现。 React提供了PropTypes来检查类型。 示例: imp...
阅读 4300·2021-11-25 09:43
阅读 2519·2021-11-23 10:13
阅读 1118·2021-11-16 11:44
阅读 2639·2019-08-29 17:24
阅读 1546·2019-08-29 17:17
阅读 3641·2019-08-29 11:30
阅读 2760·2019-08-26 13:23
阅读 2543·2019-08-26 12:10