Context 通过组件树提供了一个传递数据的方法,从而避免了在每一个层级手动的传递 props 属性。
在一个典型的 React 应用中,数据是通过 props 属性由上向下(由父及子)的进行传递的,但这对于某些类型的属性而言是极其繁琐的(例如:地区偏好,UI主题),这是应用程序中许多组件都所需要的。 Context 提供了一种在组件之间共享此类值的方式,而不必通过组件树的每个层级显式地传递 props 。
举个栗子:
点击切换语言,下面俩个button会将英文转换成中文或者中文转换成英文。
我看如何实现的。
const cnText = {
submit: '确认',
cancel: '取消'
}
const enText = {
submit: 'submit',
cancel: 'cancel'
}
const LocaleContext = React.createContext(cnText);//创建一个Context 参数是默认值
class ChangeButton extends React.Component{
constructor (props) {
super(props);
this.state = {
locale: cnText
}
}
handle = () => {
const locale = this.state.locale === enText ? cnText : enText;
this.setState({
locale
})
}
render () {
return (// value 里面为传个子组件的数据
<LocaleContext.Provider value = { this.state.locale } >
<button onClick = { this.handle } >切换语言</button>
<App />
</LocaleContext.Provider>
);
}
}
class App extends React.Component {
constructor (props) {
super(props);
this.state = enText;
}
render () {
return (
<LocaleContext.Consumer >
{ locale => (//locale 接受传过来的值,然后通过函数子组件渲染
<div>
<button> { locale.submit } </button>
<button> { locale.cancel } </button>
</div>
)}
</LocaleContext.Consumer>
);
}
}
ReactDOM.render(
<ChangeButton ></ChangeButton>,
document.getElementById('root')
)
当父组件的状态改变时,也就是通过handle函数,子组件会自动调用render重新渲染,不需要我们设置监听函数。
Context
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)