reactjs - 我想将子组件的项目从子组件设置到父组件
问题描述
我想扩展子组件中的数字,改变父组件的计数状态。如何将子组件中的数字从父组件更改为父组件的计数状态?
例如,我想在父组件按下子组件创建的标记为 12 的按钮时,将父组件的计数状态更新为 12。
父组件
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
count: ""
}
}
render() {
return (
<Child />
)
}
}
子组件
class Child extends Component {
render() {
const number = ["12", "14", "15", "16", "22", "35", "6", "92", "47", "32", "75", "67"]
return (
<div>
{(() => {
const items = [];
for (let i = 1; i <= 12; i++) {
items.push(<button>{number[i]}</button>)
};
return <>{items}</>;
})()}
</div>
)
}
}
解决方案
将一个函数从父组件传递给子组件,当单击按钮时,子组件将调用该函数,并在该函数中更新父组件的状态,例如父组件:
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
count: ""
}
}
render() {
return (
<Child onButtonClick={(number) => this.setState({count: this.state.count + number})}/>
)
}
}
子组件:
class Child extends Component {
render() {
const number = ["12", "14", "15", "16", "22", "35", "6", "92", "47", "32", "75", "67"]
return (
<div>
{(() => {
const items = [];
for (let i = 1; i <= 12; i++) {
items.push(<button onClick={() => this.props.onButtonClick(number[i])}>{number[i]}</button>)
};
return <>{items}</>;
})()}
</div>
)
}
}
推荐阅读
- python - python中的曲面图和颤动图不起作用
- mysql - 为什么我们需要嵌套的 Select 语句?
- python - pytest 是否有任何使用参数化运行的缓存?
- python - 如何在 Python 中消除我的类的属性错误?
- python - 如何遍历我的目录以附加具有 NaN 值的文件?
- c# - 参数中带有 IEnumerable 的 C# OData Web API POST 端点返回错误 400 输入无效
- node.js - 当我在单元测试中使用 firebase Cloud 功能时,某些云功能无法运行
- python - 无法从十六进制数中检索日期戳
- binding - 重新绑定智能图表,或刷新它
- mysql - 创建新表时无法获取值