我想为用户提及创建一个单独的组件。现在我有一个selectoption组件,它接受建议值并列出它们。当用户单击选项之一时,它将把所选的值返回给usermention组件。
我想以某种方式简化用户输入组件,以便在handle_change和get_comment_user_mention方法中看到的所有计算都包括在selectinput组件中。我该怎么办?
以下是我到目前为止尝试过的
class UserMention extends react.purecomponent {
constructor(props) {
super(props);
this.state = {
text: '',
suggestions: [],
};
}
user_list = [
{name: 'user2 surname'},
{name: 'tuija Rajala'},
];
handle_input_change = (event) => {
const { value } = event.target;
if (value.includes('@') && value.indexOf('@') === value.length -
1) {
this.setState({
[event.target.name]: value,
suggestions: [...this.user_mention_list],
});
} else if (value.includes('@') && value.length > 1) {
const string_after_at = value.slice(value.indexOf('@') +
1).toLowerCase();
const new_suggestions = this.user_mention_list.filter(user =>
{
return user.name.toLowerCase().includes(string_after_at);
});
this.setState({
[event.target.name]: value,
suggestions: new_suggestions,
});
} else {
this.setState({
[event.target.name]: value,
suggestions: [],
});
}
};
get_comment_with_user_mention = (comment, selected_user) => {
let user_name = selected_user;
let comment_without_user_mention;
comment_without_user_mention = comment.slice(0,
comment.lastIndexOf('@'));
if (comment_without_user_mention.length > 0) {
return ' ' + comment_without_user_mention + user_name;
} else {
return comment_without_user_mention + user_name;
}
};
handle_select_value = (selected_user) => {
let text;
text = this.get_comment_with_user_mention(this.state.new_comment,
selected_user);
this.setState({
text: text,
});
};
render = () => {
return (
<form>
<div>
<input
required
name="text"
value={this.state.text}
onChange={this.handle_input_change}
type="text"/>
<div>
<button type="submit">
<Svgsomename width="22" height="20"/>
</button>
</div>
</div>
{this.state.suggestions.length > 0 &&
<SelectInput
on_change={this.handle_select_value}
values={this.state.suggestions}/>}
</form>);
};
}
export default class SelectInput extends React.PureComponent {
handle_item_select = (value) => {
this.props.on_change(value);
};
render() {
return (
<div>
{this.props.values.map((value, index) =>
<Item
key={index}
value={value.name}
on_select={this.handle_item_select}
/>)}
</div>
);
}
}
export class Item extends React.PureComponent {
handle_item_select = e => {
this.props.on_select(this.props.value);
};
render = () => {
return (
<div onClick={this.handle_item_select}>
{this.props.value}
</div>
);
}
}
有人可以帮我解决这个问题吗?谢谢。