admin管理员组

文章数量:1417471

I have a large ponent/view that fills most the screen. I want it to show some additional information on press. Is there a way to have the main ponent catch the press event, or does it need to be caught by a child ponent inside that fills the main one (trying to avoid using an extra child to keep everything more clean)?

I would like to have something like this, even better if the onPress could be set internally:

Main View:

<MainComponent onPress={ /* Call the ponents onPress */ } />

Main Component:

export default class MainComponent extends Component {
  ...

  onPress() {
    // display additional data
  }
}

Thank you.

I have a large ponent/view that fills most the screen. I want it to show some additional information on press. Is there a way to have the main ponent catch the press event, or does it need to be caught by a child ponent inside that fills the main one (trying to avoid using an extra child to keep everything more clean)?

I would like to have something like this, even better if the onPress could be set internally:

Main View:

<MainComponent onPress={ /* Call the ponents onPress */ } />

Main Component:

export default class MainComponent extends Component {
  ...

  onPress() {
    // display additional data
  }
}

Thank you.

Share Improve this question asked Aug 26, 2017 at 20:30 gokujougokujou 1,4913 gold badges15 silver badges27 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

On React-Native, handling touches is done with Touchables ponents. (official doc)

You can use any of these native ponents depending on your use. For example, if you just want to catch the press event on your main ponent, you can wrap it under a TouchableWithoutFeedback (doc), and use the onPress prop.

export default class MainComponent extends Component {
  ...

  onPress() {
    // display additional data
  }

  ...

  render() {
    return (
        <TouchableWithoutFeedback onPress={() => this.onPress()}>
            <View>
               ...
            </View>
        </TouchableWithoutFeedback>
    )
  }
}

You can wrap your ponent in one of the ponents that is able to handle touches.

export default class MyComponent extends Component {

  render() {    
    return (
      <TouchableWithoutFeedback onPress={this.props.onPress}>
        <View>
          <Text>My Component</Text>
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

Then in Main View:

<MyComponent onPress={ () => console.log("Pressed!") } />

You can read more about handling touches in official RN docs: https://facebook.github.io/react-native/docs/handling-touches.html

本文标签: javascriptReact Native How to make a component do an action on pressStack Overflow