💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## 概述 把共享组件放入父组件的 `props`中,子组件通过父组件以`props`传入的函数传值调用父组件 ## 案例 ``` class DemoInput1 extends Component{ constructor(props) { super(props); } handleChange(e){ /* 父组件传入 onParentChange函数作为 props */ this.props.onParentChange(e.target.value) } render() { return ( <div> <input type="text" value={this.props.value} onChange={this.handleChange.bind(this)}/> </div> ) } } class DemoInput2 extends Component{ constructor(props) { super(props); } handleChange(e){ /* 父组件传入 onParentChange函数作为 props */ this.props.onParentChange(e.target.value) } render() { return ( <div> <input type="text" value={this.props.value} onChange={this.handleChange.bind(this)}/> </div> ) } } class App extends Component{ constructor(props) { super(props); this.state={ value:"", } this.onParentChange= this.onParentChange.bind(this) } onParentChange(v){ this.setState({value:v}) } render() { let value = this.state.value; return( <div> //onParentChange 函数通过 props 传入给组件 <DemoInput1 value={value} onParentChange={this.onParentChange}/> <DemoInput2 value={value} onParentChange={this.onParentChange}/> </div> ) } } ```