簡體   English   中英

React Native:如何將參數從子組件道具傳遞給父組件

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

我想創建一個在按下某個鍵時具有事件觸發器的 HOC。 當按下此鍵時,它應該向父組件提供一個事件。 在這種情況下,鍵是“@”。

兒童 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;

父組件

const UserComment = withMention(TextInput);

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

我知道實現是錯誤的,因為每當我將一個函數分配給父級子組件的 onMentionStart 道具時,子級的函數就會被父級覆蓋。 在這種情況下,如何從子組件創建自定義事件觸發器並將事件傳遞給它,以便父組件可以相應地使用它?

我實際上是通過從 HOC 中刪除 onMentionStart 道具來解決它的,並將 onMentionStart 函數從父級傳遞給子級作為回調,在 onKeyPress 處理程序函數中處理它。

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM