简体   繁体   中英

React Native: How to pass params to parent component from child component prop

I want to create a HOC that have a event trigger when a certain key is pressed. When this key is pressed it should provide an event to the parent component. In this case, the key is "@".

Child HOC

import React, { Component } from 'react';

const withMention = WrappedComponent => {
  return class extends Component {
    state = {
      mentionStart: false,
      textInput: '',
      selection: 0,
    };
    handleOnKeyPress = key => {
      if (key === '@') {
        this.setState({ mentionStart: true });
      }
    };

    render() {
      const { onMentionStart } = this.state;
      return (
        <WrappedComponent
          onChangeText={text => {
            this.setState({ textInput: text });
          }}
          onKeyPress={event => this.handleOnKeyPress(event.nativeEvent.key)}
          onSelectionChange={event =>
            this.setState({ selection: event.nativeEvent.selection })
          }
          onMentionStart={onMentionStart}
          {...this.props}
        />
      );
    }
  };
};

export default withMention;

Parent component

const UserComment = withMention(TextInput);

<UserComment onMentionStart={(event) => console.log(event)}       />

I know the implementation is wrong, because whenever I assign a function to onMentionStart prop of child component in parent, child's function is overridden by parent. In this case, how to create a custom event trigger from child component and pass event into it so that the parent can use it accordingly?

I actually solved it by removing onMentionStart prop from HOC and passed onMentionStart function from parent to child as a callback, handled it in onKeyPress handler function.

import React, { Component } from 'react';

const withMention = WrappedComponent => {
  return class extends Component {
    state = {
      mentionStart: false,
      textInput: '',
      selection: 0,
    };
    handleOnKeyPress = key => {
      if (key === '@') {
        this.setState({ mentionStart: true }, () =>
          this.props.onMentionStart(this.state.mentionStart),
        );
      }
    };

    render() {
      return (
        <WrappedComponent
          onChangeText={text => {
            this.setState({ textInput: text });
          }}
          onKeyPress={event => this.handleOnKeyPress(event.nativeEvent.key)}
          onSelectionChange={event =>
            this.setState({ selection: event.nativeEvent.selection })
          }
          {...this.props}
        />
      );
    }
  };
};

export default withMention;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM