【问题标题】:How to pass information from components to components in React?如何在 React 中将信息从组件传递到组件?
【发布时间】:2022-07-22 00:24:39
【问题描述】:

我有两个名为 <Add /><Modal> 的组件。在<Add /> 组件中,我有一个组件上的单击事件的状态。单击<Add /> 时,我将状态设置为true。我想在<Modal /> 组件中使用该状态信息。

我想根据<Add /> 组件状态的信息隐藏模式。我怎样才能做到这一点?

这是<Add /> 组件:

export default function Add() {
  const [clicked, setClicked] = useState(false)
  return(
    <div onClick={() => setClicked(true)} className={`bg-blue-500 inline-block p-4 fixed bottom-10 right-8`}>
      <FaPlus />
    </div>
  )
}

这是&lt;Modal /&gt; 组件:

export default function Modal1() {
  return (
    <div className="absolute top-1/2 left-1/2 -translate-x-1/2 translate-y-3/4">
      <div className="w-[300px] border p-4 rounded-md shadow-lg">
        <div className="inline-block my-4">
          <label className="text-xs opacity-70">Class Name</label>
          <input
            className="border py-2 px-4 rounded-md w-full"
            type="text"
            placeholder="Class Name"
          />
        </div>
        <div className="flex flex-col mb-4">
          <label className="text-xs mr-4 opacity-70">Image</label>
          <input
            className="rounded-md opacity-80"
            type="file"
            placeholder="Image"
          />
        </div>
        <div className="flex flex-row items-center justify-end">
          <button className="bg-slate-400 rounded-md px-4 py-2 mx-4 text-white">
            Cancel
          </button>
          <button className="bg-blue-500 px-4 py-2 rounded-md text-white">
            Add
          </button>
        </div>
      </div>
    </div>
  );
}

这是index.js 文件:

export default function Home() {
  return (
    <div className="relative">
      <Add />
      <Modal />
    </div>
  );
}

我正确导入了组件。我正在使用 Next.js 和 tailwindcss。

【问题讨论】:

    标签: javascript reactjs next.js tailwind-css


    【解决方案1】:

    你会想lift the state up 进入父组件

    【讨论】:

      【解决方案2】:

      所以有很多方法可以在组件之间传递数据。使用道具是更简单的一种。这是一个关于如何使用道具的 YT 视频。您还可以用户共享首选项... https://www.youtube.com/watch?v=M_Fmvs5CiDo&ab_channel=CemEygiMedia

      祝你好运

      【讨论】:

        猜你喜欢
        • 2021-11-24
        • 2019-10-19
        • 1970-01-01
        • 2020-08-21
        • 2023-03-30
        • 1970-01-01
        • 2019-08-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多