【问题标题】:I want to put my two states input data into a table in react我想将我的两种状态输入数据放入一个表中以做出反应
【发布时间】:2021-12-31 06:31:33
【问题描述】:

我想将输入数据放入表格行中。 但是我的数据使用不同的标签在不同的行上。我在导入的组件中只制作了一个标签。

这是主要组件

 import './App.css';
    import { useState } from 'react'
    import Data from './Data';
    
    function Component() {
    
        const [IdData, setIdData] = useState()
        const [Input, setInput] = useState()
        const [Items, setItems] = useState([])
    
        const addData = () => {
            setItems((newData) => {
                return [...newData, IdData, Input]
            })
           
            setInput("");
            setIdData("");
        }
    
        const idChange = (e) => {
            setIdData(e.target.value)
        }
        const inputChange = (e) => {
            setInput(e.target.value)
        }
    
      return (
        <>
          <div className="main">
    
          <div className="center">
              <br />
              <h2>Table Layout</h2>
            <div className="inner">
                <input className="id" type="number" autoFocus onChange={idChange} value={IdData} placeholder='ID' />
                <input type="text" placeholder='Name' onChange={inputChange} value={Input}/>
                <i className='fa fa-check' onClick={addData}></i>
            </div>
    
    
    
    
                {
                    Items.map((todoItems, index) => {
                        return <Data data={todoItems}key={index} />
    
                     
                    })
                }
                
            
          </div>
    
          </div>
        </>
      );
    }

export default Component;

我想将输入数据放入表格行中。 但是我的数据使用不同的标签在不同的行上。我只在导入的组件中制作了一个标签。 这是导入的组件

import React from 'react'
// import './App.css'

function Data(props) {
    return (
        <>
        <table>

            <tr>
            <th>ID</th>
            <th>Name</th>
            </tr>
            <tr>
            <tbody>
                
                <td>{props.data}</td>
            </tbody>
            </tr>
        </table>

            
                    {/* <td><i className='fa fa-times'></i></td> */}
        </>
    )
}

export default Data

我想将输入数据放入表格行中。 但是我的数据使用不同的标签在不同的行上。我在导入的组件中只制作了一个标签。

这是 CSS 文件

@import url('https://fonts.googleapis.com/css2?family=The+Nautigal:wght@700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Manrope&family=The+Nautigal:wght@700&display=swap');

* {
  padding: 0;
  margin: 0;
}
.main {
  background-image: linear-gradient(to left, #5f2c82, #49a09d);
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
p {
  display: inline;
}

.center  h2 {
  font-family: 'The Nautigal', cursive;
  font-size: 50px;
  text-align: center;
}
.center {
  /* display: flex; */
  align-items: center;
  justify-content: center;
  background: white;
  width: 40%;
  height: 80%;
  border-radius: 20px;
}
.inner {
  width: 100%;
  margin: 30px 0 0 40px;  
  display: flex;
  flex-direction: row;
  justify-content: left;
}

.data {
  /* width: 20%; */
  font-family: 'Manrope', sans-serif;
  display: flex; 
  /* flex-direction: row; */
  /* justify-self: stretch; */
  margin: 10px 39px 0 39px;
  font-size: 16px;
  background: rgb(216, 216, 216);
  /* border-radius: 10px; */
  padding: 10px 10px;
  position: relative;
  /* width: 100%;  */
}
.inline {
  display: flex;
  flex-direction: row-reverse;
}
.data:after {
  content: '';
  position: absolute;
  height: 42px;
  top: 0px;
  left: 0px;
  background: linear-gradient(to left, #5f2c82, #49a09d);
  width: 5px;
}

.data:hover {
  background: linear-gradient(to left, #5f2c82, #49a09d);
  color: white;
  cursor: pointer;
}
.inner input {
  display: flex;
  justify-content: center;
  width: 60%;
  padding: 10px 5px;
  font-size: 18px;
  border-radius: 8px;
  outline: none;
  border: 1px solid grey;
}
.inner .id {
  width: 10%;
  margin-right: 5px;
}
.fa-check {
  background: linear-gradient(to left, #5f2c82, #49a09d);
  opacity: 0.7;
  
  border-radius: 8px;
  color: white;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 9%;
  margin-left: 5px;
}

.fa-check:hover {
  cursor: pointer;
  opacity: 1;
}

【问题讨论】:

  • 您正在为每个项目创建一个新表。将您的数据传递到Data 组件并然后对其进行迭代,创建一个表示单元格数量的新行。
  • 我也试过了。但它只需要为每个项目换行。
  • 对不起,我的意思是为每一行从项目中创建单元格的数量。不过,您可能不得不重新考虑您的状态结构。我建议一个对象数组,其中每个对象都包含一个 id 和一个名称。当您添加新信息时,一个新对象被添加到状态数组中,并且它是传递给Data 的数组。然后,您可以遍历每个对象并根据其属性创建一行。

标签: javascript css arrays reactjs


【解决方案1】:

只需尝试将setITems 更改为:

setItems((newData) => {
    return [...newData].concat([[IdData, Input]]);
});

【讨论】:

  • Ashish,我又打扰你了。但是我们应该如何通过 CSS 给它们之间留出空间。我尝试了很多方法将它们分开,但由于它们在一个父项中,我们不能给它任何 prop 的子项,因为在这种情况下,值会重复自身。
  • 是的,因为您尝试在单个 中进行操作。尝试循环你的 标签&lt;tr&gt;{props.data.length &amp;&amp; props.data.map((e) =&gt; &lt;td&gt;{e}&lt;/td&gt;)}&lt;/tr&gt;
  • 这并不能真正解决问题。您仍在为每个项目/行生成一个新表。 @UsmanKhan
  • 正确,即使我建议在您的 Items.map 中的数据 > 0 后仅使用一次 。数据组件应该只返回每个数据的行
【解决方案2】:

这就是我将如何处理它。有两种状态:一种维护数据集(对象数组),另一种维护表单的当前状态(对象)。

当输入改变时,调用处理程序来更新表单状态,当点击按钮时,表单的当前状态被添加到数据集数组中。

&lt;Table&gt; 接受数据状态,因此当它发生变化时,表会发生变化。

const { useState } = React;

function Example() {

  // Initialise the states
  const [ data, setData, ] = useState([]);
  const [ form, setForm ] = useState({ id: '', name: '' });

  // I've attached one listener to the form element
  // (event delegation) which means that I need to check
  // that the event has come from the right element first,
  // and then I can update the form with
  // the name/value of the input
  function handleChange(e) {
    const { nodeName, name, value } = e.target;
    if (nodeName === 'INPUT') {
      setForm({...form, [name]: value })
    }
  }

  // Add the current form state to the dataset,
  // and reset the form
  function addEntry() {
    setData([ ...data, form ]);
    setForm({ id: '', name: '' });
  }

  // Only enable the button if both
  // fields are completed
  function isButtonDisabled() {
    return !form.id || !form.name;
  }

  return (
    <div>
      <form onChange={handleChange}>
        <fieldset>
          <legend>ID</legend>
          <input name="id" type="text" value={form.id} />
        </fieldset>
        <fieldset>
          <legend>Name</legend>
          <input name="name" type="text" value={form.name} />
        </fieldset>
        <button
          type="button"
          onClick={addEntry}
          disabled={isButtonDisabled()}
        >Add entry
        </button>
      </form>
      <Table data={data} />
    </div>
  );
};

function Table({ data }) {
  
  // Separate function to build the rows
  // from the array of objects
  function buildRows(data) {
    return data.map(obj => {
      return (
        <tr key={obj.id}>
          <td>{obj.id}</td>
          <td>{obj.name}</td>
        </tr>
      );
    });
  }
  
  // Don't show anything if the dataset is empty
  if (!data.length) return <div />;
  
  return (
    <table>
      <tbody>
        <tr className="heading">
          <td>ID</td>
          <td>Name</td>
        </tr>
        {buildRows(data)}
      </tbody>
    </table>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
button { margin-top: 1em; margin-left: auto; margin-right: auto; width: 50%; display: block; }
table { border-collapse: collapse; border: 1px solid black; margin-top: 1em; width: 75%; margin-left: auto; margin-right: auto; }
td { padding: 0.3em; border: 1px solid #565656; }
.heading { font-weight: 700; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签