reactjs - 如何将状态从子组件传递到父组件?
问题描述
我有一个名为 的父组件App
和一个名为 的子组件Left
。
Left
组件有几个组件称为Settings
和NotesList
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);
}
}
Settings
isAddNewNoteClicked
组件有一个按钮,单击时将通过true
。
状态正在顺利传递到Left
,但我的问题是isAddNewNoteClicked
从Left
到传递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);
我添加了变量本身而不是状态中的变量,它现在正在工作。
解决方案
您的 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 })
}
推荐阅读
- docker - 詹金斯步骤中的docker音量问题
- mysql - 如何将所有数据库导出为单独的 sql 文件而不是 localhost.sql
- symfony - 获取具有键和值的数组作为我在 DQL 中的选择属性
- python - 设置时出现 wxpython 错误 - ModuleNotFound:没有名为“wx”的模块
- sql - 如何在 Oracle SQL 中添加一个检查总和的约束?
- stripe-payments - Stripe Connect 更新关联账户
- micronaut - 无法在 Windows 10 上安装 micronaut
- python - 仅打印底部字符串
- java - 如何使用以下代码获得更好的性能
- f# - F# - 如何使用 fsunit 测试构造函数中引发的异常?