我知道我们可以调用像{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;
在自定义按钮类中
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;
我想通过 this.props.onPress 返回 btnName
最佳答案
<Cbuttons btnName="MainScreen" onPress={ () => { this._onBtnClick(this.props.btnName)}/>
将该字段转换为一个函数,该函数通常使用参数调用 _onBtnClick 函数。
然后您将在 _onBtnClick() 方法中反射(reflect)这一点:
_onBtnClick = buttonName => {
console.log(`Click on Button ${buttonName}`);
}
关于javascript - 通过 props onPress 传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47962396/