您可以使用“是”和“否”选项定义一个 const,如下所示
const customBool = {
YES: "Yes",
NO: "No",
};
export myBool = customBool;
然后,您可以在不同的组件中重新使用该常量
import { mybool } from "/MyFile.js";
class Hello extends React.Component {
makeYesOrNo(value) {
return b ? mybool.YES : mybool.NO;
}
render() {
let b = false;
return <span>{ this.makeYesOrNo(b) }</span>;
}
}
或者,您可以创建一个具有布尔行为但具有所需的是/否输出的类
const customBool = {
YES: "Yes",
NO: "No",
};
class YesNoBool {
constructor(shouldBeYes = false) {
this.value = shouldBeYes ? customBool.YES : customBool.NO;
}
flip() {
this.setValue(this.value == customBool.NO);
return this;
}
setValue(newValue) {
if (typeof newValue === "boolean") {
this.value = newValue ? customBool.YES : customBool.NO;
}
return this;
}
}
然后你的班级可以像这样工作:
class myClass extends React.Component {
constructor() {
super();
this.state = {
myBool5: new YesNoBool(true),
}
}
changeBool(newBool) {
this.setState({myBool5: newBool});
}
render() {
let { myBool5 } = this.state;
return(
<div>
<p>Bool 5: {myBool5.value}</p>
<button onClick={() => this.changeBool(myBool5.flip())}>Flip bool</button>
<button onClick={() => this.changeBool(myBool5.setValue(true))}>Set true</button>
<button onClick={() => this.changeBool(myBool5.setValue(false))}>Set false</button>
</div>
);
}
}
另请参阅此JSFiddle