假设我有一个自定义组件:

export default class Button extends Component {
  render(){
    return(
      <TouchOpacity>
        <Text> Button </Text>
      </TouchOpacity>
    )
  }
}

我在这样的父组件中使用它:

export default class MainPage extends Component {
  render(){
    return(
      <Button onPress={ this.doSomething }></Button>
    )
  }
}

出于某种原因(至少我不知道),这种情况甚至不会发生.

根据我上面的例子,有没有可能得到一个小例子来说明如何实现这一点?

推荐答案

所以,我刚刚发现了如何处理这个问题.

export default class Button extends Component {
  constructor(props){
    super(props)
  }
  render(){
    return(
      <TouchableOpacity
      onPress={this.props.onPress}
      >
        <Text> Button </Text>
      </TouchableOpacity>
    )
  }
}

export default class MainPage extends Component {
  render(){
    return(
      <Button onPress={ this.doSomething }></Button>
    )
  }
}

长话短说:因为我传递的onPress是主页中的一个props ,所以我传递给它一个函数(this.doSomething),它稍后会在Button的onPress中激活.

React-native相关问答推荐

如何停止在Expo路由中将新文件显示为菜单列表?

PubNubReact无法工作,因为它已被废弃

添加REACT-Native-SVG时出现错误-失败:构建失败并出现异常

TextInput 中的大写文本 - react native

错误发生意外错误:https://registry.yarnpkg.com/react-native-template-react-native-template-typescript:未找到

redux-observable 您在预期流的地方提供了 undefined

React Native WebView 中的 Javascript console.log()

react-native 中的layout-only view removal优化是什么?

给定 APK 文件,我如何检测应用程序是否使用 React Native?

你如何使 react-native react-navigation 标签栏透明

如何在 React-Native Android 中检测拖动事件的结束

使用 React Navigation 制作离开屏幕的动画

React Native 使视图 Hug键盘顶部

Jest 的配置在更新到 26.x 后抛出type ErrorHandler = (error: mixed, isFatal: boolean) => void

React native Redux - 对象不是构造函数(判断'new ctor(props context)')

Animated.View 的样式props的Typescript定义

对未计算文件的本机Bundle sha-1 做出react(无法从assets index.android.bundle 加载脚本)

运行 expo start 时如何禁用在浏览器中打开 DevTools?

如何设置样式属性以填充剩余空间?

在 React Native 中将props传递给外部样式表?