我正在测试 React 的 Context API,并成功地将我的状态项和方法传递给 Consumer 组件。但是,当我向该方法添加一些条件逻辑时,我失去了对状态对象项的引用。我收到“无法读取未定义的属性‘颜色’”错误。如何在该状态对象中按颜色键引用,以便运行逻辑?我可以在 Provider 组件中执行此操作,还是只能在 Consumer 组件中执行此逻辑?
提供者容器文件 - ProviderComp.js
class ProviderComp extends Component{
state={
name: "Gary",
age: 20,
color: "Red",
changeMind: function(){
if(this.color === "Red"){
document.getElementById("root").style.background="blue";
document.getElementById("root").style.color="white";
this.setState({
name: "Tony",
age: 35,
color: "Blue"
})
}
if(this.color === "Blue"){
document.getElementById("root").style.background="red";
document.getElementById("root").style.color="black";
this.setState({
name: "Gary",
age: 20,
color: "Red"
})
}
}
}
render(){
return(
<UserInfo.Provider value={{state:this.state}}>
{this.props.children}
</UserInfo.Provider>
)
}
}
export default ProviderComp;
消费者组件 - ConsumerComp.js
import React, {Component} from "react";
import UserInfo from "./ContextData";
class ConsumerComp extends Component{
render(){
return(
<UserInfo.Consumer>
{(context)=>(
<React.Fragment>
<p>My Name Is: {context.state.name}</p>
<p>My Age Is: {context.state.age}</p>
<p>My Favorite Color Is: {context.state.color}</p>
<button onClick={context.state.changeMind}>Changed My Mind</button>
</React.Fragment>
)}
</UserInfo.Consumer>
)
}
}
export default ConsumerComp;