[英]In REACT.js how can I pass a state from child component up to Parent component as a prop
[英]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.