javascript - 通过 props onPress 传递值

标签 javascript react-native react-props

我知道我们可以调用像{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/

相关文章:

react-native - Flatlist keepVisibleContentPosition 导致 iO 上立即崩溃

android - 在 React Native 中添加产品 flavor 的正确方法是什么?

javascript - 通过 JavaScript 设置 HTML 表单图像输入的 'capture' 属性

javascript - 如何将 jQuery 功能与分组元素分组?

Android studio 错误 - 使用 firebase react native

javascript - 无法调用 props 子函数

reactjs - Prop 类型失败 : Component: prop type `props` is invalid;

reactjs - 如何将函数作为 props 从功能父组件传递给子组件

javascript - Node JS 中的 AES 加密/解密类似于 Java

javascript - WebStorm 修复所有 TSLint 错误就是修复除一个错误之外的所有错误