[英]How to send an array from child component to parent component in react?
I am creating a react application where I have to send an array from child component to parent component.我正在创建一个反应应用程序,我必须将一个数组从子组件发送到父组件。 I am trying to send using callback function now but its not working.
我现在正在尝试使用回调 function 发送,但它不起作用。
Here's my child component:这是我的子组件:
var apis=[]
export default class ApiDropDown extends React.Component {
constructor() {
super();
this.state = {
options: [],
suboptions: [],
};
}
componentDidMount() {
this.fetchOptions();
}
fetchOptions() {
fetch("http://localhost:5000/groups")
.then((res) => {
return res.json();
})
.then((json) => {
this.setState({ options: json });
});
}
//SETTING THE apis here,just adding few elements,its a long function
onSubmit()
{
this.props.apisgranted(apis)
}
render() {
return (
<div>
<button type="button" className="btn" onSubmit={this.onSubmit}> //Save button to set data in the prop.
Save
</button>
</div>
);
}
}
Now here's my parent component:现在这是我的父组件:
const AddTask = ({ onAdd, onStatusChange }) => {
const [client_name, setText] = useState("");
const [status, setStatus] = useState("");
const [showMessage,setMessage]=useState(false)
const [apigrants,setapigrants]=useState([])
const handleApiGrants = (langValue) => {
setapigrants(langValue) //setting the props array here from child component
console.log(apigrants) //nothing gets printed here
}
return (
<form className="add-form" onSubmit={onSubmit}>
<div>
<button onClick={setmessage.bind(false, true)} type="button" className="btn">Grant API's</button>
{ showMessage && (<ApiDropDown apisgranted={handleApiGrants} />) } //calling the props handling function where which should set the apigrants array with props array.
</div>
In my child component,I am using onSubmit
function to set the array to prop.在我的子组件中,我使用
onSubmit
function 将数组设置为 prop。 In my parent component,First i am declaring apigrants
array as empty and later assigning it to prop array from child component using handleApiGrants
function.在我的父组件中,首先我将
apigrants
数组声明为空,然后使用handleApiGrants
function 从子组件将其分配给 prop 数组。
The easiest way to do that would be to define the variable in the parent component and also pass it down to the child, like you do with handleApiGrants最简单的方法是在父组件中定义变量并将其传递给子组件,就像使用 handleApiGrants 一样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.