在像C#这样的语言中,可能有一个基于其他属性的属性。让我们假设我们有Name
和Surname
属性。然后,我们可以定义DisplayName
属性
get { return $"{this.Name} {this.Surname}"; }
我想知道这在带有状态属性的React中是否可行。将函数定义为状态变量的值是合法的:
state = {
isSomethingTrue: function() {
return true;
},
};
但是,我们需要执行此函数来获取值。有什么方法可以通过调用this.state.isSomethingTrue
来返回计算出的值吗?
答案 0 :(得分:1)
您可以这样实现该功能:
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>;
}
}
这是演示:
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>;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
答案 1 :(得分:-2)
最好将其作为使用状态的类中的自由函数或私有方法来完成。
const isSomethingTrue(state) => state.thing === 42;
或
class Comp ... {
isSomethingTrue = () => this.state.thing === 42;
}