gpt4 book ai didi

javascript - 如何在 React 中的兄弟组件之间进行通信

转载 作者:行者123 更新时间:2023-12-05 01:53:56 25 4
gpt4 key购买 nike

请问如何将 Prop 从一个 sibling 转移到另一个 sibling ?

在主应用程序中,我只有 2 个 sibling :

输入:

import React from "react";

const Input = () => {
return (
<>
<label htmlFor="name">Full Name</label>
<input type="text" id="name" placeholder="TheDareback" />
<label htmlFor="job">Job Title</label>
<input type="text" id="job" placeholder="Frontend Developer" />
</>
);
};

export default inputDetails;

预览:

import React from "react";

const Preview = () => {
return (
<>
<table>
<thead>
<tr>
<th>{/* here I need a Full Name from the input */}</th>
<th>{/* here I need a Job Title from the input*/}</th>
</tr>
</thead>
</table>
</>
);
};

export default Preview;

我尝试将 useEffect 添加到 Preview 以读取每个输入的值。

例如

  const name = document.querySelector("#name");
const [inputName, setInputName] = useState("TheDareback");

useEffect(() => (name.value ? setInputName(name.value) : null));

但我仍然遇到错误:

Preview.js:9 Uncaught TypeError: 无法读取 null 的属性(读取“值”)

是否可以仅在第二次渲染时运行 useEffect?或者,除了直接从 Input.js 移动 Prop 之外,还有其他选择吗?我会在哪里为输入中的每个 onChange 创建一个处理程序?

非常感谢您朝着正确的方向前进。

最佳答案

您需要某种容器组件(例如 App.js),您可以在那里有一个输入状态,以及一个传递给输入组件的 inputHandler 函数,并将其与 onChange 一起放置。

import React, {useState} from 'react';

export default function Container() {
const [input, setInput] = useState({
name: '',
job: ''
})

const inputHandler = (e, type) => {
setInput(prevState => ({...prevState, [type]: e.target.value}))
}
return (
<>
<Input onInputChange={inputHandler} />
<Preview input={input} />
</>
);
}

输入:

const Input = ({onInputChange}) => {
return (
<>
<label htmlFor="name">Full Name</label>
<input type="text" id="name" placeholder="TheDareback" onChange={(e) => onInputChange(e, 'name')} />
<label htmlFor="job">Job Title</label>
<input type="text" id="job" placeholder="Frontend Developer" onChange={(e) => onInputChange(e, 'job')} />
</>
);
};

export default Input;

预览:

const Preview = ({input}) => {
return (
<>
<table>
<thead>
<tr>
<th>{input.name}</th>
<th>{input.job}</th>
</tr>
</thead>
</table>
</>
);
};

export default Preview;

关于javascript - 如何在 React 中的兄弟组件之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70908353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com