小编Jur*_*ian的帖子

如何将 React Hook 传递给子组件

我想将 React Hook 的 setter 传递给子组件。以便子组件中的按钮通过保存在父组件中的 setter 更新状态。我尝试了以下设置,但收到一条错误消息:

类型错误:setshowOptionPC 不是 onClick 函数

我的方法甚至可能吗?如果不是,我怎么可能使用 React Hook 来做这个结构。

下面是我的代码的简化版本:

import React, { useState } from "react";

function ChildComponent({ setshowChildOptionBC, setshowChildOptionPC }) (
  <div>
    <button
      onClick={() => {
        setshowChildOptionPC(false);
        setshowChildOptionBC(true);
      }}
    >
      BC
    </button>
    <button
      onClick={() => {
        setshowChildOptionPC(true);
        setshowChildOptionBC(false);
      }}
    >
      PC
    </button>
  </div>
);


function ParentComponent() {
  const [showOptionBC, setshowOptionBC] = useState(true);
  const [showOptionPC, setshowOptionPC] = useState(false);

  return (
    <div>
      <ChildComponent
        setshowChildOptionBC={setshowOptionBC}
        setshowChildOptionPC={setshowOptionPC}
      />
      {showOptionBC && <div>BC</div>}
      {showOptionPC && <div>PC</div>}
    </div> …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs

4
推荐指数
1
解决办法
7529
查看次数

如何将 react-hook-form 组合成组件

我第一次尝试使用react-hook-formhttps://react-hook-form.com/)。我不知道如何用 redux 将它们组合成反应组件。

import React from 'react'
import useForm from 'react-hook-form'

export default function SampleForm() {
    const { register, handleSubmit, watch, errors } = useForm()
    const onSubmit = data => { console.log(data) }

    console.log(watch('example')) // watch input value by passing the name of it

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <input name="example" defaultValue="test" ref={register} />
            <input name="exampleRequired" ref={register({ required: true })} />
            {errors.exampleRequired && <span>This field is required</span>}
            <input type="submit" />
        </form>
    );
}
Run Code Online (Sandbox Code Playgroud)
import React, { Component …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hook-form

4
推荐指数
1
解决办法
5784
查看次数

标签 统计

reactjs ×2

javascript ×1

react-hook-form ×1