gpt4 book ai didi

javascript - react native : How to pass params to parent component from child component prop

转载 作者:行者123 更新时间:2023-12-04 10:48:04 24 4
gpt4 key购买 nike

我想创建一个在按下某个键时具有事件触发器的 HOC。当按下此键时,它应该向父组件提供一个事件。在这种情况下,键是“@”。

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;


父组件
const UserComment = withMention(TextInput);

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

我知道实现是错误的,因为每当我将一个函数分配给父级子组件的 onMentionStart Prop 时,子级的函数就会被父级覆盖。在这种情况下,如何从子组件创建自定义事件触发器并将事件传递给它,以便父组件可以相应地使用它?

最佳答案

我实际上是通过从 HOC 中删除 onMentionStart Prop 来解决它的,并将 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;

关于javascript - react native : How to pass params to parent component from child component prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59611916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com