1

我知道我们可以像这样调用函数{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

4

2 回答 2

2
<Cbuttons btnName="MainScreen" onPress={ () => { this._onBtnClick(this.props.btnName)}/>

将该字段转换为一个函数,该函数通常使用参数调用 _onBtnClick 函数。

然后你会在 _onBtnClick() 方法中反映这一点:

_onBtnClick = buttonName => {
        console.log(`Click on Button ${buttonName}`);
}
于 2017-12-24T16:58:21.440 回答
1

这解决了我的问题,谢谢@mcpolo

class MyButtons extends Component {
  render(){
    return(
      <TouchableOpacity  onPress={()=>{this.props.onPress(this.props.btnName)}} >
        <Text style={yourStyles.buttonText}> {this.props.btnName}</Text>
      </TouchableOpacity>
    );
  }
}
于 2017-12-24T17:12:17.060 回答