我试图函数handleClick
到我的按钮onPress
绑定。但它不工作。当我刷新页面,我得到的警告没有点击该按钮后,我关闭警告并点击按钮,没有任何反应。
我的代码是:
class ActionTest extends Component {
constructor(props) {
super(props);
this.state = {
thename: 'somename'
};
}
handleClick(){
alert('Button clicked!');
}
render(){
return(
<View>
<Button
onPress={this.handleClick()}
title="Click ME"
color="blue"
/>
</View>
);
}
}
我也得到警告:
我究竟做错了什么?
要调用handleClick当它呈现为你onPress={this.handleClick()}
尝试onPress={this.handleClick}
而是通过它的函数作为回调。
首先定义你的点击处理程序作为一个箭头的功能。这样,你就不需要功能了绑定。你的函数将是这样的:
handleClick = () => {
alert('Button clicked!');
}
那么在这样的<Button>
标签使用此功能:
<Button
onPress={this.handleClick}
title="Click ME"
color="blue"
/>
当反应本土检测到点击事件,并希望通知你,它会调用onPress
道具的功能。所以你必须给一个函数来onPress
道具,如:
onPress={this.handleClick}
这个连接onPress
到handleClick
方法。但如果你想打电话给在handleClick
其他方法,你需要“this
对象”,你可以通过handleClick
方法是这样的:
onPress={this.handleClick.bind(this)}
祝好运
更新你的代码!你应该通过参考
<Button
onPress={this.handleClick}
title="Click ME"
color="blue"
/>
你可以试试吗
class ActionTest extends Component {
constructor(props) {
super(props);
this.state = {
thename: 'somename'
};
}
handleClick=()=>{
alert('Button clicked!');
}
render(){
return(
<View>
<Button
onPress={this.handleClick}
title="Click ME"
color="blue"
/>
</View>
);
}
}
如果您定义功能出你的类的范围还没有使用this
关键字与您的处理函数
喜欢
//function moved here
const handleClick = () => {
alert('Button clicked!');
}
class ActionTest extends Component {
constructor(props) {
super(props);
this.state = {
thename: 'somename'
};
}
render(){
return(
<View>
<Button
onPress={handleClick()}
title="Click ME"
color="blue"
/>
</View>
);
}
}