[英]I can't update state in child component
我想更改子组件中的 state 值,但我总是收到“this.setState is not a function”错误
父组件
`
export default class Todo extends Component {
constructor(props){
super(props)
this.state = {
propBottomMenu : false
}
this.bottomRef = React.createRef()
};
checkClose(){
this.setState({propBottomMenu : false})
}
render() {
return (
<>
// other codes
<TouchableOpacity
onPress={() => this.setState({propBottomMenu : false})}
style={styles.addTask}
>
<FontAwesomeIcon icon={ faPlus } size={25} color={'#fff'} />
</TouchableOpacity>
{this.state.propBottomMenu ?
<BottomMenu bSheetRef={this.bottomRef} checkClose={this.checkClose} style= {styles.bottomMenu} />
: null}
</>
)
}
}
`
子组件:
`
export default class BottomMenu extends Component {
constructor(props){
super(props)
this.bottomRef = this.props.bSheetRef
}
render() {
return (
<>
<BottomSheet
ref={this.bottomRef}
snapPoints={[ '40%', '60%', '90%']}
index={1}
enablePanDownToClose={true}
onChange={(index)=>{ index < 0 && this.props.checkClose() }}
>
// other codes
</BottomSheet>
</>
)
}
}
})
`
checkClose() function 工作但我无法更新 state
错误:this.setState 不是 function
解决方案:要使 function 正常工作,我们必须使用绑定或将其称为箭头 function
constructor(props){
super(props)
this.checkClose = this.checkClose.bind(this); // this line
this.state = {
propBottomMenu : false
}
this.bottomRef = React.createRef()
};
Jsx:
<BottomMenu bSheetRef={this.bottomRef} checkClose={this.checkClose} style={styles.bottomMenu} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.