Isa*_*ton 0 javascript reactjs
我正在尝试构建这个 React 组件。addEntry 检测用户何时提交数据条目,RenderTable 应该以表行格式呈现每个条目:
import React, { useState, setState } from 'react';
import ReactDOM from 'react-dom'function
function addEntry({ addEntryData }) {
const data = [{
First: "aaa",
Last: "bbb",
Phone: 123123
}];
const [contact, setContact] = useState(data);
const submitEntry = (e) => {
e.preventDefault();
setContact(contact.push({
First: e.target.userFirstname.value,
Last: e.target.userLastname.value,
Phone: e.target.userPhone.value
}))
}
return (
<form onSubmit={submitEntry} style={style.form.container}>
<input
className='userFirstname'
name='userFirstname'
type='text'
/>
<input
className='userLastname'
name='userLastname'
type='text'
/>
<input
className='userPhone'
name='userPhone'
type='text'
/>
<input
className='submitButton'
type='submit'
value='Add User'
/>
</form>
)
};
function RenderTable(props) {
return (
<table className='informationTable'>
<thead>
<tr>
<th style={style.tableCell}>First name</th>
<th style={style.tableCell}>Last name</th>
<th style={style.tableCell}>Phone</th>
</tr>
</thead>
</table>
);
}
function Application(props) {
return (
<section>
<addEntry/>
<RenderTable/>
</section>
);
Run Code Online (Sandbox Code Playgroud)
我想将contact数据从addEntryto传递RenderTable,这样RenderTable可以生成一些行。但我尝试过 props 或 call RenderTable(contact)。Contact好像只住里面addEntry,而不是RenderTable。我应该怎么做才能RenderTable读取变量中存储的值contact?
这个问题的解决方案很少。可能最简单的方法是创建一个useStateinApplication组件,将更新函数传递给addEntry(建议:将其命名为AddEntry)并将状态传递给RenderTable。基本上,将您的状态从addEntry组件移至Application组件。我认为该表将包含联系人列表。
function Application(props) {
const [contacts, setContacts] = useState([]);
return (
<section>
<addEntry setContacts={setContacts}/>
<RenderTable contacts={contacts}/>
</section>
);
Run Code Online (Sandbox Code Playgroud)
并addEntry添加道具setContacts:
function addEntry({ addEntryData, setContacts }) {
const submitEntry = (e) => {
e.preventDefault();
setContacts((contacts) => [...contacts, {
First: e.target.userFirstname.value,
Last: e.target.userLastname.value,
Phone: e.target.userPhone.value
}])
}
...
}
Run Code Online (Sandbox Code Playgroud)
更干净的解决方案:使用一些全局状态管理库,例如 Redux 或 React context。