【发布时间】:2017-08-21 20:01:14
【问题描述】:
我是 react native、react.js 和 javascript 方面的新手。我是 Android 开发人员,所以想试试 RN。
基本上,区别就在onPress;
此代码在 toggle() 运行时显示 'undefined':
class LoaderBtn extends Component {
constructor(props) {
super(props);
this.state = { loading: false };
}
toggle() {
console.log(this.state);
// let state = this.state.loading;
console.log("Clicked!")
// this.setState({ loading: !state })
}
render() {
return (
<Button style={{ backgroundColor: '#468938' }} onPress={this.toggle}>
<Text>{this.props.text}</Text>
</Button>
);
}
}
但这段代码有效:
class LoaderBtn extends Component {
constructor(props) {
super(props);
this.state = { loading: false };
}
toggle() {
console.log(this.state);
// let state = this.state.loading;
console.log("Clicked!")
// this.setState({ loading: !state })
}
render() {
return (
<Button style={{ backgroundColor: '#468938' }} onPress={() => {this.toggle()}}>
<Text>{this.props.text}</Text>
</Button>
);
}
}
你能解释一下区别吗?
在Java / Kotlin中我们有方法引用,基本上如果签名相同,它就会传递函数,比如onPress = () => {}和toggle = () => {}
但是在 JS 中它不起作用:(
【问题讨论】:
标签: javascript reactjs react-native