[英]How do I send an array to a child component in React?
I want to send the array inputArrival and inputBurst to the child component Barchart.js.我想将数组 inputArrival 和 inputBurst 发送到子组件 Barchart.js。 But whenever I do this only the first element which I enter is being sent and not the other items.
但是每当我这样做时,只会发送我输入的第一个元素,而不是其他项目。 Basically what I want is that as the data is being entered into the Entrytable.js it is instantly reflected.
基本上我想要的是,当数据被输入到 Entrytable.js 时,它会立即得到反映。 EntryTable.js
EntryTable.js
import React,{useState} from 'react';
import './tableEdit.css';
import Barchart from './Barchart';
const EntryTable = (props) => {
const entry = props.numOfEntries;
const [inputArrival, setInputArrival] = useState(Array(entry).fill(""));
const [inputBurst, setInputBurst] = useState(Array(entry).fill(""));
function changeArrival(index) {
return (e) => {
setInputArrival((values) =>
values.map((value, i) => (i === index ? e.target.value : value)));};
}
function changeBurst(index) {
return (e) => {
setInputBurst((values) =>
values.map((value, i) => (i === index ? e.target.value : value))
);
};
}
const ArrayEntry = Array.from({ length: entry}).map((_, i) => (
<tr key={i}>
<td >P{i}</td>
<td >
<input
type="number"
value={inputArrival[i]}
onChange={changeArrival(i)}
/>
ms
</td>
<td >
<input
type="number"
value={inputBurst[i]}
onChange={changeBurst(i)}
/>
ms
</td>
</tr>
));
return (
<div c>
<table>
<thead>
<tr>
<th>Process</th>
<th>Arrival Time</th>
<th>Burst Time</th>
</tr>
</thead>
<tbody>{ArrayEntry}</tbody>
</table>
<button>Click Me</button>
<Barchart selected_val={entry} arrivalArray={inputArrival} ></Barchart>
</div>
);
};
export default EntryTable
Barchart.js条形图.js
import React,{useState,useEffect} from 'react'
const Barchart=(props)=>{
const sel = props.selected_val;
var ar1=props.arrivalArray;
console.log(ar1);
}export default Barchart;
As far as i got your question, im not sure where is the problem:至于我得到你的问题,我不确定问题出在哪里:
First: As Tasos said converted all the variables to let
;首先:正如 Tasos 所说,将所有变量转换为
let
;
Second: Assigned a value of 5 for the const entry
image here第二:这里给
const entry
图片赋值5
Third: Added one more prop for the other array of data you want, and pass it to the child component Barchart.js
;第三:为您想要的其他数据数组添加了一个道具,并将其传递给子组件
Barchart.js
; image here图片在这里
And this is the result: image here这就是结果:图片在这里
Ran your code and even though you have some improvements to add to it, other than this it seems to work.运行你的代码,即使你有一些改进要添加到它,除此之外它似乎工作。
The only difference is returning something in Barchart.js
.唯一的区别是在
Barchart.js
中返回一些东西。 Maybe try to return null in Barchart.js
, it might throw a silent error.也许尝试在 Barchart.js 中返回
Barchart.js
,它可能会抛出一个静默错误。
I recommend using a linter also for code styling.我建议也使用 linter 进行代码样式设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.