Mri*_*agi 4 javascript reactjs react-native expo
我正在React Native
为我的应用程序使用,有一次,我注意到this.state.bar[this.state.foo][SOME_NUMBER]
每次必须在组件中键入内容。
这工作得很好,但是我想通过调用一个函数来使代码更整洁。因此,我构造了这个:
function txt(n){
return this.state.bar[this.state.foo][n];
}
Run Code Online (Sandbox Code Playgroud)
但是,当我在Expo
客户端中运行此命令时,出现以下错误:
TypeError: undefined is not an object (evaluating 'this.state.bar')
This error is located at:
in App...
....
Run Code Online (Sandbox Code Playgroud)
这是我的整个代码。
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试将text()
函数放置在App
类之外,但遇到相同的错误。
当我将它放在外面render()
时App
,出现了unexpected token
错误。
当我定义this.state
内constructor(props)
,并放置text()
内的constructor
,我ReferenceError: Can't find variable: text
您的问题是范围界定。
在this
你试图向里面接入txt()
功能是指向自己的this
,而不是外部组件this
。
有几种方法可以解决此问题。这里是一些:
您可以转换txt
为箭头函数以使用外部函数this
:
render() {
const txt = (n) => {
return this.state.bar[this.state.foo][n];
}
return (
<View>
...
</View>
);
}
Run Code Online (Sandbox Code Playgroud)
this
render() {
function _txt(n){
return this.state.bar[this.state.foo][n];
}
const txt = _txt.bind(this);
return (
<View>
...
</View>
);
}
Run Code Online (Sandbox Code Playgroud)
this
render() {
const self = this;
function txt(n){
return self.state.bar[self.state.foo][n];
}
return (
<View>
...
</View>
);
}
Run Code Online (Sandbox Code Playgroud)
txt
函数移到render函数之外,并将其绑定到组件this
。this
。...而且我敢肯定还有其他几种方法可以解决此问题。您只需要知道何时使用组件this
或其他组件即可this
。
归档时间: |
|
查看次数: |
6575 次 |
最近记录: |