[英]How can I get all the values from multiple select inputs on a button click? React
I'm creating a questionnaire where the values of the select inputs are collected and averaged to produce a score.我正在创建一个调查问卷,其中收集并平均选择输入的值以产生分数。 Seems easy enough, but I'm struggling to get them.
看起来很容易,但我正在努力获得它们。 Currently my goal is just to get the values to begin with, but it seems like I can only get the value for the last select input when I click the submit button, calling the
handleClick()
event.目前我的目标只是获取开始的值,但似乎我只能在单击提交按钮时获取最后一个选择输入的值,调用
handleClick()
事件。
I'm not sure if I'm doing it right.我不确定我是否做得对。 Through some guides I've seen others use the
useRef()
function, but I've seen the createRef()
as well.通过一些指南,我看到其他人使用
useRef()
函数,但我也看到了createRef()
函数。
I'm using Gatsby JS and GraphQL for the data query.我使用 Gatsby JS 和 GraphQL 进行数据查询。 I appreciate any advice.
我很感激任何建议。
const Questionnaire = (props: Props) => {
const data = props.data!
const questionnaire = data.allContentfulQuestionnaire.edges
let i = 0
const selectInput = useRef()
const handleClick = () => {
for (const r in selectInput) {
console.log("foo: ", selectInput.current.value)
console.log("bar: ", r.valueOf())
}
}
return (
<Layout>
<Container>
{questionnaire?.map(({ node }: any) => (
<>
<h2>{node?.title}</h2>
{node?.questions?.map(({ answers, question }: any) => (
<Question key={question?.id}>
<P>
{++i}. {question?.question}
</P>
<select key={question?.id} ref={selectInput}>
<option>Select Response</option>
{answers.map(({ title, id, score }: any) => (
<option key={id} value={score}>
{title}
</option>
))}
</select>
</Question>
))}
</>
))}
<Submit onClick={handleClick}>Submit</Submit>
</Container>
</Layout>
)
}
If you want to go with ref, you need n
ref for n
fields/select如果要使用 ref,则需要
n
ref 用于n
字段/选择
const Questionnaire = (props: Props) => { const data = props.data! const questionnaire = data.allContentfulQuestionnaire.edges let i = 0 const refs = node?.questions?.map(q => q.node?.questions?.map(useRef)); const handleClick = () => { // You have nested array of refs so you can get the desired values console.log(refs[0][0].current.value); } return ( <Layout> <Container> {questionnaire?.map(({ node }: any, outerIndex) => ( <> <h2>{node?.title}</h2> {node?.questions?.map(({ answers, question }: any, innderIndex) => ( <Question key={question?.id}> <P> {++i}. {question?.question} </P> <select key={question?.id} ref={refs[outerIndex][innderIndex]}> <option>Select Response</option> {answers.map(({ title, id, score }: any) => ( <option key={id} value={score}> {title} </option> ))} </select> </Question> ))} </> ))} <Submit onClick={handleClick}>Submit</Submit> </Container> </Layout> ) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.