【问题标题】:How can I get all the values from multiple select inputs on a button click? React如何在单击按钮时从多个选择输入中获取所有值?反应
【发布时间】:2020-04-01 11:37:23
【问题描述】:

我正在创建一个调查问卷,其中收集所选输入的值并对其进行平均以产生分数。看起来很容易,但我很难得到它们。目前我的目标只是获取值开始,但似乎我只能在单击提交按钮时获取最后一个选择输入的值,调用handleClick() 事件。

我不确定我是否做得对。通过一些指南,我看到其他人使用useRef() 函数,但我也看到了createRef()

我正在使用 Gatsby JS 和 GraphQL 进行数据查询。我很感激任何建议。

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>
  )
}

【问题讨论】:

  • 为什么不在选择时使用on change callback ??
  • useRef 仅适用于一个上下文。
  • 反应滥用 - 避免在 DOM 中保持状态...useState ...阅读反应文档/教程(处理事件)!

标签: javascript reactjs graphql gatsby ref


【解决方案1】:

如果你想使用 ref,你需要 n ref for n fields/select

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>
  )
}

【讨论】:

  • 感谢您的回复!!我将questonnaire 添加到const refs = questionnaire?.node?.questions?.map((q: any) =&gt; { q.questionnaire?.node?.questions?.map(useRef) }),因为它表示未定义节点。目前我在&lt;select key={question?.id} ref={refs[outerIndex][innerIndex]}&gt; 收到错误“TypeError:无法读取未定义的属性'0'”。有任何想法吗?再次感谢您的帮助!
  • 有没有console.log(refs),它的值是多少
  • 分页符出现同样的错误:“TypeError: Cannot read property '0' of undefined”
  • const refs 赋值后代码不应中断,在此处打印
猜你喜欢
  • 2018-03-20
  • 2021-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
相关资源
最近更新 更多