reactjs - ReactJS 在父类中使用子道具
问题描述
我有一个父类,它使用它的子类从数组“days”中呈现一些按钮。到目前为止,这工作正常。我使用处理程序将 handleClick() 传递给孩子。这也有效,如果没有 if 语句,我会在控制台中获得返回。我的代码有什么问题或考虑 if 语句有什么问题。如果我单击值为 days[0] = 1 的按钮,它应该回复“Hi 1”。
家长:
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
days: [1,2,3]
}
}
handleClick() {
if(this.props.value === 1) {
return console.log('Hi 1')
}
}
render() {
return (
<div>
<div>
{this.state.days.map(item => <ButtonDays handler={ () => this.handleClick()} key={item} value={item} />)}
</div>
</div>
);
}
}
孩子:
export default class ButtonDays extends React.Component {
render() {
return (
<Button onClick={this.props.handler}>{this.props.value}</Button>
);
}
}
解决方案
在您的父组件的以下部分
handleClick() {
if(this.props.value === 1) {
return console.log('Hi 1')
}
}
您正在检查名为 的道具value
,但此道具仅在您的子组件中定义。
您应该做的是将单击的值作为handler
函数的参数传递。
<Button onClick={() => this.props.handler(this.props.value)}>{this.props.value}</Button>
然后在您的父组件中:
handleClick(value) {
if(value === 1) {
return console.log('Hi 1')
}
}
推荐阅读
- python - 使用错误输入时出现循环值错误
- android - 检索孩子的其他值
- python - 如何使用 Q 对象应用条件 AND 语句
- scala - 在 Scala 中继续 for 循环
- r - 有没有一种聪明的方法可以将 R 宽数据收集到需要收集数百个不同变量的长数据?
- flutter - 如何使用按钮转到特定页面?扑
- python - Python列表理解/三元运算符:如果条件,则附加递增值,否则附加非递增值
- r - 更改属于同一组的行的值并且该组中至少有一个观察符合 dplyr 的条件
- vue.js - Vuex - 分配了mapState值的局部变量,改变局部变量也会改变存储变量?
- python - 每次迭代时保存 DataFrame