Javascript 是否可以在React中定义计算的状态变量?

Javascript 是否可以在React中定义计算的状态变量?,javascript,reactjs,Javascript,Reactjs,在像C#这样的语言中,有一个基于其他属性的属性是可能的。让我们假设我们有名称和姓氏属性。然后我们可以定义DisplayName属性 get { return $"{this.Name} {this.Surname}"; } 我想知道这是否在React中,以及状态属性中是可能的。将函数定义为状态变量的值是合法的: state = { isSomethingTrue: function() { return true; }, }; 然而,我们需要执行这个函数来获得值。有没有办法这

在像C#这样的语言中,有一个基于其他属性的属性是可能的。让我们假设我们有
名称
姓氏
属性。然后我们可以定义
DisplayName
属性

get { return $"{this.Name} {this.Surname}"; }
我想知道这是否在React中,以及状态属性中是可能的。将函数定义为状态变量的值是合法的:

state = {
  isSomethingTrue: function() {
    return true;
  },
};

然而,我们需要执行这个函数来获得值。有没有办法这样做,调用
this.state.isSomethingTrue
将只返回计算值?

这最好作为使用状态的类中的自由函数或私有方法来完成

const isSomethingTrue(state) => state.thing === 42;


最好在使用状态的类中作为自由函数或私有方法来完成

const isSomethingTrue(state) => state.thing === 42;


您可以实现如下功能:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: "Hello"
    };
  }
  get isSomethingTrue() {
    return this.state.message + " World";
  }
  render() {
    return <div>{this.isSomethingTrue}</div>;
  }
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
留言:“你好”
};
}
获取isSomethingTrue(){
返回this.state.message+“World”;
}
render(){
返回{this.isSomethingTrue};
}
}
这是演示:

类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
留言:“你好”
};
}
获取isSomethingTrue(){
返回this.state.message+“World”;
}
render(){
返回{this.isSomethingTrue};
}
}
const rootElement=document.getElementById(“根”);
render(,rootElement)

您可以实现如下功能:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: "Hello"
    };
  }
  get isSomethingTrue() {
    return this.state.message + " World";
  }
  render() {
    return <div>{this.isSomethingTrue}</div>;
  }
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
留言:“你好”
};
}
获取isSomethingTrue(){
返回this.state.message+“World”;
}
render(){
返回{this.isSomethingTrue};
}
}
这是演示:

类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
留言:“你好”
};
}
获取isSomethingTrue(){
返回this.state.message+“World”;
}
render(){
返回{this.isSomethingTrue};
}
}
const rootElement=document.getElementById(“根”);
render(,rootElement)


Q特别提到了这种已知的方式,要求不需要函数调用的替代方法。Q特别提到了这种已知的方式,要求不需要函数调用的替代方法。@ChrisG这就是我要找的:)@ChrisG这就是我要找的:)