我有一个名为 的父组件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);
我添加了变量本身而不是来自状态的变量,它现在正在工作。
好的,所以添加这一行
this.props.onNewNote(isAddNewNoteClicked);
在onNewNote()
我的功能上<Left />
修复了这个问题。
希望它帮助别人!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句