Javascript 使用react钩子将所选项目显示给另一个组件
我有一个包含模板的部分,现在我想让用户选择一个模板,并编辑模板中的数据,如姓名、职务、联系人等 这是我在代码沙盒中的实时演示 这里是templates.jsJavascript 使用react钩子将所选项目显示给另一个组件,javascript,html,reactjs,forms,react-hooks,Javascript,Html,Reactjs,Forms,React Hooks,我有一个包含模板的部分,现在我想让用户选择一个模板,并编辑模板中的数据,如姓名、职务、联系人等 这是我在代码沙盒中的实时演示 这里是templates.js export default function Templates() { const [selected, setSelected] = useState(""); let history = useHistory(); const handleSelected = (e) => { con
export default function Templates() {
const [selected, setSelected] = useState("");
let history = useHistory();
const handleSelected = (e) => {
const value = e.target.innerHTML;
setSelected(value);
history.push('/Settings')
};
return (
<div className="App">
<h2>Select one of the Template below by clicking title</h2>
<div className={`template_one ${selected === "Template_one" ? "selected" : "unselected"}`} onClick={(e) => {setSelected(selected !== "Template_one" ? "Template_one" : ""); handleSelected(e);}}>
<h1>Template_one</h1>
<table striped bordered hover size="sm">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Job</th>
<th>Facebook</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<th>Developer</th>
<td>facebook/Mark</td>
</tr>
</tbody>
</table>
</div>
<div className={`template_two ${selected === "Template_two" ? "selected" : "unselected"}`} onClick={(e) => {setSelected(selected !== "Template_two" ? "Template_two" : "");handleSelected(e);}}>
<h1>Template_two</h1>
<table striped bordered hover size="sm">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Job</th>
<th>Company</th>
<th>Contact </th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Trump</td>
<th>President</th>
<td>Trump Organization</td>
<td>+1 728 256 345</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
这里是settings.js
import React from "react";
export default function Settings() {
return (
<div>
<h1>Settings</h1>
<div className="Settings">
<form>
Name: <input type="text" name="firstname" />
Job: <input type="text" name="job" /> <br />
Facebook: <input type="text" name="facebook" />
Company: <input type="text" name="company" />
Contact: <input type="text" name="contact" />
</form>
<div className="selected-template">
Here should be the selected template
</div>
</div>
</div>
);
}
预期结果:
问题:我不知道如何在设置组件中显示所选模板
如何将所选模板复制到“设置”组件,以便用户可以编辑所选模板?我不知道为什么,但有人删除了我的其他帖子,这就是我现在看到你的消息的原因。如果您想制作不同的样式,可以将类名添加到数据中。如果你愿意,你也可以看看这个图书馆:它在用户中非常流行。您可以使用这个库基本上用javascript制作所有样式。如果要使用这个库,可以在数据中添加所有JS。 下面是一个例子: 常数表1={ 根目录:{ 背景:“线性梯度45度,FE6B8B 30%,FF8E53 90%, 边界:0, 边界半径:3, boxShadow:'0 3px 5px 2px rgba255、105、135、.3', 颜色:'白色', 身高:48, 填充:“0 30px”, }, }; 资料=[ { 名字:'某物', 风格:表1 }, { 年龄:22,, 风格:表2 }
]没有任何理由认为我应该在父组件中保留数据,而我将拥有数百个模板,它的坏习惯是将所有内容都包含在父组件中,这里的问题不是应用程序结构,问题是如何向设置组件显示所选元素,就是这样,我想这就是你想要的:我改变了设置、应用程序和索引。现在你可以在表单下看到你选择的项目,我刚刚将“selected”和“setSelected”从templates.js移到index.js,所以现在所有组件都可以使用“selected”和道具。我将在几个小时内给出基于数据的表模板的示例。现在,您可以使用changeOnData函数更改数据。我认为您的问题在于使用js dom。你应该用react state而不是js-dom来更改和获取值。没问题,很高兴我能帮上忙:有人删除了我的另一篇文章,这就是为什么我用你最后一个问题的答案编辑了这篇文章。