首页 > 解决方案 > 如何将状态从子组件传递到父组件?

问题描述

我有一个名为 的父组件App和一个名为 的子组件Left

Left组件有几个组件称为SettingsNotesList

class Left extends Component {
  constructor() {
    super();

    this.state = { isAddNewNoteClicked: false };
  }

  render() {
    return (
      <section>
        <Settings onNew={this.onNewNote.bind(this)} />
        <NotesList newNote={this.state.isAddNewNoteClicked} />
      </section>
    );
  }

  onNewNote = (isAddNewNoteClicked) => {
    this.setState({ isAddNewNoteClicked });

    {/* SEE EDIT */}
    {/* this.props.onNewNote(this.state.isAddNewNoteClicked); */}

    {/* SEE EDIT #2 */}
    this.props.onNewNote(isAddNewNoteClicked);
  }
}

SettingsisAddNewNoteClicked组件有一个按钮,单击时将通过true

状态正在顺利传递到Left但我的问题是isAddNewNoteClickedLeft到传递App

<App />看起来像这样

class App extends Component {
  constructor() {
    super();

    this.state = { isAddNewNoteClicked: false };
  }

  onNewNote = () => {
    console.log('test');
  }

  testFunction(a) {
    console.log('test', a);
  }

  render() {
    return (
      <main className="App">
        <Left onNew={this.testFunction.bind(this)} />
        <Right isAddNewNoteClicked={ this.state.isAddNewNoteClicked } />
      </main>
    );
  }
}

编辑

所以我添加this.props.onNewNote(this.state.isAddNewNoteClicked);onNewNote我的<Left />组件上的函数中,它现在正在调用该函数,但是 `' 上的状态没有被更新......

编辑#2

而不是this.props.onNewNote(this.state.isAddNewNoteClicked);我添加了变量本身而不是状态中的变量,它现在正在工作。

标签: reactjs

解决方案


您的 Left 组件没有调用通过 App.props 传递给它的 onNew 函数。这部分

onNewNote = (isAddNewNoteClicked) => {
  this.setState({ isAddNewNoteClicked });
}

只会设置 Left 的状态,直到您调用 this.props.onNew()

编辑

在左边

onNewNote = (isAddNewNoteClicked) => {
  this.setState({ isAddNewNoteClicked });
  this.props.onNew(isAddNewNoteClicked); // Notice you calling it "onNew", not "onNewNote"
}

在应用程序上

testFunction(isAddNewNoteClicked) {
  this.setState({ isAddNewNoteClicked })
}

推荐阅读