Javascript 通过props onPress传递值
我知道我们可以像Javascript 通过props onPress传递值,javascript,react-native,react-props,Javascript,React Native,React Props,我知道我们可以像{this.props.onPress}那样调用函数,我们也可以使用这个回调传递值吗?已传递默认对象,但我想使用此函数传递字符串值。这是可能的,我张贴我的代码来清除这种情况 import Cbuttons from './../utils/CustomButtons' class MainScreen extends Component { _onBtn
{this.props.onPress}
那样调用函数,我们也可以使用这个回调传递值吗?已传递默认对象,但我想使用此函数传递字符串值。这是可能的,我张贴我的代码来清除这种情况
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;
从“/../utils/CustomButtons”导入Cbuttons
类MainScreen扩展组件{
_onBtnClick=event=>{
日志(“点击按钮”);
}
render(){
返回(
);
}
}
导出默认主屏幕;
当按下按钮时
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;
类MyButtons扩展组件{
建造师(道具){
超级(道具);
this.state={btnName:this.props.btnName};
}
render(){
返回(
{this.props.btnName}
);
}
}
导出默认按钮;
我想通过这个.props.onPress返回btnName这解决了我的问题,谢谢@mcpolo
<Cbuttons btnName="MainScreen" onPress={ () => { this._onBtnClick(this.props.btnName)}/>
class MyButtons extends Component {
render(){
return(
<TouchableOpacity onPress={()=>{this.props.onPress(this.props.btnName)}} >
<Text style={yourStyles.buttonText}> {this.props.btnName}</Text>
</TouchableOpacity>
);
}
}
类MyButtons扩展组件{
render(){
返回(
{this.props.onPress(this.props.btnName)}>
{this.props.btnName}
);
}
}
该函数位于this.props.onPress中调用this.props.onPress
将传递组件本身,要传递附加信息,我们需要将其转换为函数并在该函数体中调用。如果要调用多个函数,则this.props.onPress将不起作用。请使用this.props.onPress()。。。。谢谢我从你的回答中得到了这个想法
class MyButtons extends Component {
render(){
return(
<TouchableOpacity onPress={()=>{this.props.onPress(this.props.btnName)}} >
<Text style={yourStyles.buttonText}> {this.props.btnName}</Text>
</TouchableOpacity>
);
}
}