问题描述
我在访问输入值时遇到问题,我在这里使用的是 .map()。
这是代码,<QuestionLabel/>
是子组件。 projectsData.projectDetail
是可用数据
//..
{projectsData.projectDetail.questions.map((question) => (
<QuestionLabel
questionTitle={question}
/>
))}
//child component
const QuestionLabel=(props)=>{
const [answerInput,setAnswerInput] = React.useState("");
return(
<div className="contact">
<form className="contact-form" autocomplete="off">
<div class="contact-form-group">
<label
for="name"
class="contact-form-label"
>
{props.questionTitle}
</label>
<input
id="name"
type="text"
class="contact-form-input"
value={answerInput}
onChange={(answer) => setAnswerInput(answer.target.value)}
/>
</div>
</form>
</div>
);
}
export default QuestionLabel;
解决方法
有很多方法可以从子组件中获取价值以作为父组件。您可以调用从父级到子级的函数传递,以在value
设置为parent state
时对其进行更改。例子:
const ParentComponent =(props)=>{
const [valueFromChild,setValueFromChild] = useState('');
return <>
{valueFromChild}
<QuestionLabel questionTitle={'Title'} setValueFromChild={setValueFromChild}/>
</>
}
const QuestionLabel=(props)=>{
const [answerInput,setAnswerInput] = React.useState("")
useEffect(() => {
props.setValueFromChild(answerInput);
},[answerInput]);
return(
<div className="contact">
<form className="contact-form" autoComplete="off">
<div class="contact-form-group">
<label
for="name"
class="contact-form-label"
>
{props.questionTitle}
</label>
<input
id="name"
type="text"
class="contact-form-input"
value={answerInput}
onChange={(answer) => setAnswerInput(answer.target.value)}
/>
</div>
</form>
</div>
);
}
,
因此,您需要在父级中设置输入状态。
由于您要遍历问题数组以呈现QuestionLabel
,所以我们可以尝试...
//..
const ParentComponent = () => {
const [answers,setAnswers] = React.useState({})
useEffect(() => {
projectsData.projectDetail.questions.forEach((_,i) => {
setAnswers(previousAnswers => {...previousAnswers,["name" + i]: ""})
})
},[])
const handleAnswers = (e) => {
setAnswers(previousAnswers => {...previousAnswers,[e.target.name]: [e.target.value]})
}
//..
然后
//..
{
projectsData.projectDetail.questions.map((question,i) => {
return (
<QuestionLabel questionTitle={question} inputName={"name" + i} answers={answers} handleAnswers={handleAnswers} />
)
})
}
最后...
//child component
const QuestionLabel=(props)=>{
return(
<div className="contact">
<form className="contact-form" autocomplete="off">
<div class="contact-form-group">
<label
for={props.inputName}
class="contact-form-label"
>
{props.questionTitle}
</label>
<input
id={props.inputName}
name={props.inputName}
type="text"
class="contact-form-input"
value={answers[props.inputName]}
onChange={handleAnswers}
/>
</div>
</form>
</div>
);
}
export default QuestionLabel;