javascript - React Native: How to make a component do an action on press - Stack Overflow

I have a large ponentview that fills most the screen. I want it to show some additional information on

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745266401a4619483.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信