从子级调用回调函数时,React-props为空
React - props is empty when calling a callback function from child
我的主组件上有一个按钮,当它被点击时,会打开一个"审批面板",当点击OK时,我会调用主组件的回调函数并执行一些逻辑。
我想传递回调函数(我的原因),问题是当调用回调函数时,props和state是未定义的。
为什么会发生这种情况?如果缺少任何信息,请告诉我。
我在这里添加了一个部分代码:
class MainComponent extends React.Component {
constructor(props){
currentActionConfig = {onOkClick: this.onGenericApprovalOkClicked, ...};
}
onCommandApprovalOkClicked(commandText){
console.log(this.props); <- 'undefined'
}
render(){
return <ActionsApprovalPanel currentActionConfig={this.currentActionConfig}/>
}
}
export default class ActionsApprovalPanel extends React.Component {
render()
{
...
return <ChangeIpApproval onOkClick={this.props.currentActionConfig.onOkClick}/>;
...
}
}
尝试这些更改
class MainComponent extends React.Component {
constructor(props){
super(props); //1. Call super
this.currentActionConfig = {onOkClick: this.onGenericApprovalOkClicked.bind(this), ...}; // 2.bind this
}
onCommandApprovalOkClicked(commandText){
console.log(this.props); <- 'undefined'
}
render(){
return <ActionsApprovalPanel currentActionConfig={this.currentActionConfig}/>
}
}
export default class ActionsApprovalPanel extends React.Component {
render()
{
...
return <ChangeIpApproval onOkClick={this.props.currentActionConfig.onOkClick}/>;
...
}
}
我认为您需要对React组件进行一些更改。
第一个:在构造函数中调用super()
。
第二::将currentActionConfig
定义为一个状态,并尝试将其用作this.state.currentActionConfig
第三个:指定onCommandApprovalOkClicked()
上的绑定。像CCD_ 5和用于其它功能的类似物。
class MainComponent extends React.Component {
constructor(props){
super(props);
this.state = {
currentActionConfig = {onOkClick: this.onGenericApprovalOkClicked, ...}
};
}
onCommandApprovalOkClicked(commandText){
console.log(this.props); <- 'undefined'
}
render(){
return <ActionsApprovalPanel currentActionConfig={this.state.currentActionConfig}/>
}
}
export default class ActionsApprovalPanel extends React.Component {
render()
{
...
return <ChangeIpApproval onOkClick={this.props.currentActionConfig.onOkClick}/>;
...
}
}
进行这些更改,看看它们是否有效。
相关文章:
- 如果文本字段为空,则使用JavaScript应用CSS样式
- ReactJS映射:如何仅在url变量不为空时呈现html链接
- 如果localstorage为空,则显示欢迎消息
- 使用 jQuery 检查所有值是否为空或已填充
- 如果值为空,如何设置输入的默认值?jQuery
- React 15使用空字符串删除输入值
- 如何检查元素的内容是否为空,如果为空,请在jquery中删除该元素
- 在MVC 4中,对Controller的Ajax调用为空
- 未捕获的类型错误:无法读取属性'状态'在react中为null
- Spring Ajax列表返回,但对象为空
- 输入文本框为空时的阻止按钮asp.网络表单
- $_POST变量为空
- 如果数据为空,Ajax加载不会停止
- 边框颜色是't如果输入为空,则更改
- React/Redux 状态在第二次操作调用时为空
- 警告:React.createElement:类型不应为空、未定义、布尔值或数字
- Reactjs:警告:React.createElement: type不应该为空或未定义
- React控制的组件输入值为空字符串
- React组件this.ops始终为空
- 从子级调用回调函数时,React-props为空