企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
~~~ constructor(props) { super(props) // 状态(数据)提升 ,把数据放在最高层的组件中,直接下方给子组件 this.state = { list: [ { id: 'id-1', title: '标题1' }, { id: 'id-2', title: '标题2' }, { id: 'id-3', title: '标题3' } ], footerInfo: '底部文字' } } ~~~ 子组件 ~~~ class Input extends React.Component { constructor(props) { super(props); this.state = { title: '' } } render() { return <div> <input value={this.state.title} onChange={this.onTitleChange}/> <button onClick={this.onSubmit}>提交</button> </div> } onTitleChange = (e) => { this.setState({ title: e.target.value }) }; onSubmit = () => { const { submitTitle } = this.props submitTitle(this.state.title); // 'abc' this.setState({ title: '' }) } } ~~~ 父组件 ~~~ render() { return <div> <Input submitTitle={this.onSubmitTitle}/> <List list={this.state.list}/> <Footer text={this.state.footerInfo} length={this.state.list.length}/> </div> } onSubmitTitle = (title) => { this.setState({ list: this.state.list.concat({ id: `id-${Date.now()}`, title }) }) } ~~~