Reactjs 无法在另一个函数内运行函数:无法读取属性';测试';未定义/无法读取属性';设置状态';未定义的
我想从onClose()函数运行回调测试()。我试图在StackOverflow中找到解决方案,但无法解决问题。运行这段代码会给我在带有代码块的注释中提到的未定义错误Reactjs 无法在另一个函数内运行函数:无法读取属性';测试';未定义/无法读取属性';设置状态';未定义的,reactjs,Reactjs,我想从onClose()函数运行回调测试()。我试图在StackOverflow中找到解决方案,但无法解决问题。运行这段代码会给我在带有代码块的注释中提到的未定义错误 constructor(props){ super(props) this.state = { isPaid: false } this.test = this.test.bind(this) } test = () =>{ const { isPaid } = t
constructor(props){
super(props)
this.state = {
isPaid: false
}
this.test = this.test.bind(this)
}
test = () =>{
const { isPaid } = this.state
console.log(isPaid)
this.setState({isPaid: true})
}
render() {
const isPaid = this.state
const {test} = this.props
let config = {
"publicKey": "*****",
"productIdentity": "1234567890",
"eventHandler": {
onSuccess (payload) {
console.log(payload);
},
onError (error) {
// handle errors
console.log(error);
},
onClose (){
console.log('widget is closing');
//Want to add some callback here to test()
const {test} = this.props //The issue is here
console.log(test) //getting Undefined
test(); //TypeError: Cannot read property 'test' of undefined
//OR
console.log(isPaid) //I get state as log
this.setState({isPaid: !isPaid}) //TypeError: Cannot read property 'setState' of undefined
}
}
};
let checkout = new paygateway(config);
return (
<div>
<button onClick={ () => {checkout.show({amount: 1000})} }>Test</button>
</div>
)
构造函数(道具){
超级(道具)
此.state={
isPaid:错
}
this.test=this.test.bind(this)
}
测试=()=>{
const{isPaid}=this.state
控制台日志(isPaid)
this.setState({isPaid:true})
}
render(){
const isPaid=this.state
const{test}=this.props
让配置={
“公钥”:“*******”,
“产品标识”:“1234567890”,
“eventHandler”:{
onSuccess(有效载荷){
控制台日志(有效载荷);
},
onError(错误){
//处理错误
console.log(错误);
},
onClose(){
log(“小部件正在关闭”);
//想在这里添加一些回调来测试()吗
const{test}=this.props//问题就在这里
console.log(test)//未定义
test();//类型错误:无法读取未定义的属性“test”
//或
console.log(isPaid)//我将状态获取为log
this.setState({isPaid:!isPaid})//TypeError:无法读取未定义的
}
}
};
let checkout=new paygateway(配置);
返回(
{checkout.show({amount:1000}}}>Test
)
您正在从这个.props解构测试
,而该函数在props中不存在。它只是您在组件中声明的一个函数。因此,您应该将测试变量分配给测试函数,如下所示:
const test = this.test
您正在从
this.props解构测试,而该函数在props中不存在。使用const test=this.test