javascript - 在方法中反应更新状态并传递它
问题描述
我正在尝试更新方法 start() 中的状态,然后将状态的值传递给 MyComponent。我的组件工作正常,当我在类中设置它时状态更新正常,但是当我试图从 start 方法传递它时 - 它不起作用。得到“TypeError:this.setState 不是函数”
已编辑 - 固定绑定,但仍然无法正常工作。
可能是什么问题?
export default class App extends Component{
constructor (props){
super(props);
this.state = {
val: false
}
this.start= this.start.bind(this)
}
start() {
this.setState({ val: true })
}
render(){
return (
<View>
<Button
title='start'
onPress={this.start}>
</Button>
<MyComponent value={this.state.val}> </MyComponent>
</View>
);
}
}
这是我的组件:
class MyComponent extends Component {
constructor(props){
super(props)
this.state={}
this.state.custum={
backgroundColor: 'red'
}
let intervalid;
if (this.props.value){
setTimeout(() => {
this.setState( {
custum:{
backgroundColor: 'green'
}
})
}, 1000);
setTimeout(() => {
this.setState( {
custum:{
backgroundColor: 'red'
}
})
}, 2000);
}
}
render() {
return (
<View style={[styles.old, this.state.custum]}>
</View>
);
}
}
var styles = StyleSheet.create({
old:{
padding: 5,
height: 80,
width: 80,
borderRadius:160,
},
})
export default MyComponent;
解决方案
您必须将上下文绑定到您的函数。
constructor (props){
super(props);
this.state = {
val: false
}
this.start = this.start.bind(this)
}
或者只是您可以使用箭头功能,无需绑定
start = () => {
this.setState({ val: true })
}
推荐阅读
- javascript - React native:通过 2 个组件将图像路径作为参数传递
- php - 在 PHP 7.3.6 -RHEL 7.6 中安装 mcrypt
- java - 部署为战争时 SFTP 入站同步失败
- firebase - 为什么 firebase 服务抛出错误而不是 firebase 部署?
- ios - 为什么 Swift 的 AVPlayer 中存在 mp3 延迟?
- ios - Swift 是否有办法不仅观察对象的变化,还观察引用的变化?
- microsoft-graph-api - 尝试打开 Onedrive 文件选择器时如何修复 System.UnauthorizedAccessException 错误?
- swiftui - 如何在表单部分中的 SwiftUI 文本视图中显示多行?
- crash - Xcode 11 Beta 7 在设备上运行但不在画布或模拟器中时崩溃
- linux - 为什么 Linux 中的 NPTL 线程仍然为每个线程分配唯一的 PID?