javascript - 如何将值从子功能组件传递给父类组件?
问题描述
我有一个父类组件和一个子功能组件。我们如何将这种类型的子组件的值传递给父组件 - 我已经看到了一些将值从子类组件传递到父类组件的示例。
父组件
import React from "react";
import ChildComponent from "./ChildComponent/ChildComponent";
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [] // An index value is in this state
};
}
render(){
//can console log the return value from the ChildComponent here if needed
return(
<React.Fragment>
<ChildComponent indexval = {this.state.data.index} />
</React.Fragment>
)
}
}
export default ParentComponent;
一个 propindexval
被传递给子组件,它是一个功能组件,如下所示
子组件
import React from 'react';;
import Button from './Button/Button';
function ChildComponent(props) {
const newVal=(index) => {
let retVal = index + 1; //the retValue need to pass to the parent component
}
return (
<React.Fragment>
<Button onClick={() => newVal(props.index)}>Click</Button>
</React.Fragment>
)
}
您可以注意到 ChildComponent 有一个retVal
需要传递给父组件的值。我们怎样才能做到这一点
解决方案
父组件
import React from "react";
import ChildComponent from "./ChildComponent/ChildComponent";
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [] // An index value is in this state
};
}
handleClick = (value) => {
// handle changes from child
console.log(value)
}
render(){
return(
<React.Fragment>
// 1. we pass function for child on props
<ChildComponent handleClick={this.handleClick} indexval = {this.state.data.index} />
</React.Fragment>
)
}
}
export default ParentComponent;
子组件
import React from 'react';;
import Button from './Button/Button';
function ChildComponent(props) {
const newVal=(index) => {
let retVal = index + 1;
// 2. do calculations and send it to parent
props.handleClick(retVal);
}
return (
<React.Fragment>
<Button onClick={() => newVal(props.index)}>Click</Button>
</React.Fragment>
)
}
推荐阅读
- javascript - JQuery how to match values of a text area to an array?
- sql - 将日期转换为浮点数会丢失两天
- r - 如何在 r 中使用 ggplot 生成买入卖出交易信号
- docker - 码头工人:码头工人还是码头工人.io?
- postgresql - Postgresql:多维数组追加
- polymer - Polymer 3.0 多选类似于 select2 库多选
- java - Why escaping double quote with single and triple backslashes in a Java regular expression yields identical results
- vba - ListObject("Table1").DataBodyRange.PasteSpecial 出现 438 错误
- python - 在线程 Virtualbox 中运行正常和调试的不同行为
- jquery - 将 .on 绑定到 jquery 中的功能