【发布时间】:2017-10-06 23:13:04
【问题描述】:
我正在尝试通过另一个组件更改我的一个组件的状态。请注意,我是 reactJs 新手
在我的父母组件中,我有一个名为:_SPCommandBarDisabled
this.state = {
_SPCommandBarDisabled: true
}
在 child 组件(SPSearchBox)中,触发了更改 _SPCommandBarDisabled 状态的事件(日志显示状态为实际改变了)
public onSearchTextChanged(newText: any) {
this.setState({ _SPCommandBarDisabled: false },
() => { console.log("New _SPCommandBarDisabled: " + this.state._SPCommandBarDisabled) }
);
但是,在我的第二个孩子(SPCommandBar 组件)中,该值没有更新。
这是我的父母组件
export default class StudentDocumentsHelper extends React.Component<IStudentDocumentsHelperProps, any> {
constructor() {
super();
this.state = {
_SPCommandBarDisabled: true
}
this.onSearchTextChanged = this.onSearchTextChanged.bind(this);
}
public render(): React.ReactElement<IStudentDocumentsHelperProps> {
return (
<div>
<SPCommandBar isDisabled={this.state._SPCommandBarDisabled} />
<SPSearchBox onTextChange={this.onSearchTextChanged} />
<SPListView />
</div>
);
}
public onSearchTextChanged(newText: any) {
this.setState({ _SPCommandBarDisabled: false },
() => { console.log("New _SPCommandBarDisabled: " + this.state._SPCommandBarDisabled) }
);
}
}
SPCommandBar 继承自 props
export interface ISPCommandBar {
isDisabled: boolean;
}
export class SPCommandBar extends React.Component<ISPCommandBar, any> {
constructor(props: any) {
super(props);
this.state = {
_SPCommandBarDisabled: this.props.isDisabled
};
}
更新
在我的 SPCommandBar 组件中,我继承了 _SPCommandBarDisabled 属性并将其解析为状态。
在我的 SPCommandBar 的 render() 方法中,我通过引用状态来设置 enabled 值:
disabled: this.state._SPCommandBarDisabled
当更新父状态时,子状态似乎没有更新。但是,当引用道具而不是它正在工作的状态时:
disabled: this.props.isDisabled
我想知道我是否只是解决了自己的问题,还是这不是应该这样做?
【问题讨论】:
标签: javascript reactjs typescript webpack state