从另一个更新一个 React 的组件状态

Updating one React's components state from another

我正在尝试通过另一个组件更改我的一个组件的状态。请注意,我是 reactJs 的新手

在我的 parents 组件 中,我有一个名为的状态: _SPCommandBarDisabled

this.state = {
  _SPCommandBarDisabled: true
}

child 组件(SPSearchBox)中触发的事件改变了 _SPCommandBarDisabled(日志显示状态确实改变了)

public onSearchTextChanged(newText: any) {
this.setState({ _SPCommandBarDisabled: false },
  () => { console.log("New _SPCommandBarDisabled: " + this.state._SPCommandBarDisabled) }
);

但是,在我的第二个 child(SPCommandBar 组件)中,该值没有更新。

这是来自我的 parents 组件

的代码
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
        };
    }

Update

在我的 SPCommandBar 组件中,我继承了 _SPCommandBarDisabled 属性并将其解析为状态。

在我的 SPCommandBar 的 render() 方法中,我通过引用状态设置 enabled 值:

disabled: this.state._SPCommandBarDisabled

并且在更新 parents 状态时,child 状态似乎没有得到更新。但是,当提到道具而不是它正在工作的状态时:

disabled: this.props.isDisabled

我想知道我是否刚刚解决了我自己的问题,或者这不是应该的方式吗?

在原始发布者找到解决方案后进行编辑:

构造函数只会被调用一次,在创建组件时,当你传递给组件的props发生变化时,不会再次调用构造函数,而是componentWillReceiveProps,你可以阅读更多here

原答案:

我认为错误是您使用的是 this.props,而不仅仅是 props(在构造函数的定义中传递)

尝试改变这个:

this.state = {
    _SPCommandBarDisabled: props.isDisabled
};