我正在尝试使用带有onAdd功能的react-mentions库作为道具,一旦用户从呈现的建议中选择了一个值,就会触发该库。我使用了相同的钩子,但是当我设置注释的值时,即使在onChange事件触发后调用了onAdd函数,该数据也是陈旧的。这是相同的代码段
import React, { useState, useEffect } from "react";
import { MentionsInput, Mention } from "react-mentions";
const MyComponent = props => {
let [comment, setComment] = useState("");
function onAdd(id, display) {
// Do something here
console.log("Comment inside onAdd: ", comment);
}
function handleCommentChange(e) {
// Handle the changes in the textArea
console.log("from handleCommentChange: ", e.target.value);
setComment(e.target.value);
}
function renderSuggestion(entry, search, highlightedDisplay, index, focused) {
// Modify the suggestion dropdown by returning valid JSX
return (
<>
<span>{entry.display}</span>
</>
);
}
function handleSubmitComment(e) {
e.preventDefault();
// Do something to submit comment
}
return (
<>
<MentionsInput
markup="@[__display__](__id__)"
value={comment}
onChange={handleCommentChange}
placeholder={"Mention people using '@'"}
>
<Mention
trigger="@"
data={[{
id: "1",
display: "Jimmy"
},
{
id: "2",
display: "Ketut"
},
{
id: "3",
display: "Gede"
}]}
renderSuggestion={renderSuggestion}
onAdd={onAdd}
appendSpaceOnAdd={true}
/>
</MentionsInput>
<button onClick={handleSubmitComment}>Comment</button>
</>
);
};
export default MyComponent;
现在,当我从handleCommentChange console.log中检查它时,如果我选择Jimmy,它的值就是@Jimmy,但是在onAdd函数中它仍然是@
哪个是注释的先前值,而不是当前值。我是刚接触钩子的新手,想知道我在这里想念什么?