[英]Passing a value via props onPress
I know we can call the function like {this.props.onPress}
, can we pass value using this callback too? 我知道我们可以像
{this.props.onPress}
那样调用函数,我们也可以使用这个回调传递值吗? Default object is passed but I want to pass a string value using this function. 传递默认对象但我想使用此函数传递字符串值。 Is this possible, I'm posting my code to clear the situation.
这是可能的,我发布我的代码来清除这种情况。
import Cbuttons from './../utils/CustomButtons'
class MainScreen extends Component {
_onBtnClick = event => {
console.log("Click on Button");
}
render() {
return (
<View style={customStyles.mainContainer}>
<Cbuttons btnName="MainScreen" onPress={this._onBtnClick}/>
<Cbuttons btnName="ScreenTwo" onPress={this._onBtnClick}/>
<Cbuttons btnName="ScreenThree" onPress=
{this._onBtnClick}/>
</View>
);
}
}
export default MainScreen;
while inCustom Buttons clsss 而在自定义按钮clsss
class MyButtons extends Component {
constructor(props){
super(props);
this.state={btnName:this.props.btnName};
}
render(){
return(
<TouchableOpacity onPress={this.props.onPress} >
<Text style={yourStyles.buttonText}> {this.props.btnName}</Text>
</TouchableOpacity>
);
}
}
export default MyButtons;
I want to return btnName back via this.props.onPress 我想通过this.props.onPress返回btnName
<Cbuttons btnName="MainScreen" onPress={ () => { this._onBtnClick(this.props.btnName)}/>
Turn that field into a function which calls the _onBtnClick function normally with a parameter. 将该字段转换为一个函数,该函数通常使用参数调用_onBtnClick函数。
Then you would reflect that in the _onBtnClick() method: 然后你会在_onBtnClick()方法中反映出来:
_onBtnClick = buttonName => {
console.log(`Click on Button ${buttonName}`);
}
This solved my problem, Thanks @mcpolo 这解决了我的问题,谢谢@mcpolo
class MyButtons extends Component {
render(){
return(
<TouchableOpacity onPress={()=>{this.props.onPress(this.props.btnName)}} >
<Text style={yourStyles.buttonText}> {this.props.btnName}</Text>
</TouchableOpacity>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.