我在应用程序中使用React Native
,有一次,我注意到我每次都必须在我的组件中键入this.state.bar[this.state.foo][SOME_NUMBER]
.
这很好用,但我想通过调用函数来让代码更简洁.所以,我构建了这个:
function txt(n){
return this.state.bar[this.state.foo][n];
}
然而,当我在Expo
客户机上运行这个时,我得到了以下错误:
TypeError: undefined is not an object (evaluating 'this.state.bar')
This error is located at:
in App...
....
这是我的全部代码.
import React,
{ Component }
from 'react';
import {
...
} from 'react-native';
export default class App extends React.Component {
state = {
foo: 'ABC',
bar: {
'ABC': [
'...',
'...',
'...'
]
}
};
render() {
function txt(n){
return this.state.bar[this.state.foo][n];
}
return (
<View>
...
</View>
);
}
}
我try 将text()
函数放在App
类之外,但得到了相同的错误.
当我把它放在App
的render()
之外时,我得到了一个unexpected token
错误.
当我在constructor(props)
中定义了this.state
,在constructor
中定义了text()
,我得到了ReferenceError: Can't find variable: text