我试图了解 ReactJs 上下文,并最终在显示状态名称和 countNumber 方面取得了一些进展。
但是,我仍在努力解决如何替换当前状态,该状态在我的 formatCount() 函数中使用。
谁能在下面的示例中告诉我您将如何做到这一点?
我想在我的上下文中使用数字,例如方法 formatCount() 中的 5,所以它类似于
formatCount() {
const currentCount = {c.state.currentCount};
return currentCount === 0 ? "Zero" : currentCount;
}
这是我的上下文
import React, { Component } from "react";
export const CounterContext = React.createContext();
export default class CounterProvider extends Component {
state = {
state: { name: 'bob', currentCount: 5 },
}
render() {
return (
<CounterContext.Provider value={ this.state }>
{this.props.children}
</CounterContext.Provider>
)
}
}
这是我的计数器组件
import React, { Component } from "react";
import { RouteComponentProps } from "react-router";
import { CounterContext } from "../contexts/context.js";
export class Counter extends Component {
state = { currentCount: 7 }
render() {
return <div className="m-2">
<CounterContext.Consumer>
{c =>
<div className="m-2">
<p>My name is {c.state.name} - {c.state.currentCount}</p>
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button className="btn btn btn-primary btn-sm m-2" onClick={() => { this.incrementCounter() }}>Increment</button>
<button className="btn btn-danger btn-sm m-2" onClick={() => { this.incrementCounter() }}>Delete</button>
</div>
}
</CounterContext.Consumer>
</div>;
}
formatCount() {
const currentCount = this.state.currentCount;
return currentCount === 0 ? "Zero" : currentCount;
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.currentCount === 0 ? "warning" : "primary";
return classes;
}
incrementCounter() {
this.setState({
currentCount: this.state.currentCount + 1
});
}
}