[英]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.我想创建一个在按下某个键时具有事件触发器的 HOC。 When this key is pressed it should provide an event to the parent component.当按下此键时,它应该向父组件提供一个事件。 In this case, the key is "@".在这种情况下,键是“@”。
Child 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;
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.我知道实现是错误的,因为每当我将一个函数分配给父级子组件的 onMentionStart 道具时,子级的函数就会被父级覆盖。 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.我实际上是通过从 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.