这里组件间参数传递只限利用回调传递即子组件向父组件传值。(父组件向子组件传值用props,多层级或无关联组件传参用三方啦 只用过redux其他不清楚)
注:传值1、2、3、4分别为组件内有默认、组件内无默认、组件间有默认、组件间无默认。点击事件也有默认传值...
组件内(无默认值和有默认值情况)
class Demo extends Component{ constructor(props){ super(props); this.state={ value:'', externalValue:'', refresh:true, }; } onClick =(value) =>{ console.log(`点击${value}` ); this.setState({refresh:!this.state.refresh}); }; OnChange =value=> (e) =>{ console.log(value); console.log(e.target.value); this.setState({value:e.target.value}) }; render(){ return( <div> <div> <input value={this.state.value} onChange={this.OnChange(1)}/> </div> <div> <button onClick={()=>this.onClick(2)}>11</button> </div> </div> ); } }注意两种情况为避免函数立即执行的写法
组件间(无默认值和有默认值情况)
export default class Demo extends Component{ constructor(props){ super(props); this.state={ value:'', externalValue:'', refresh:true, }; } onClick =(value) =>{ console.log(`点击${value}` ); this.setState({refresh:!this.state.refresh}); }; OnChange =value=> (e) =>{ console.log(value); console.log(e.target.value); this.setState({value:e.target.value}) }; OnExterChange =(value ,e)=>{ console.log(value); this.setState({externalValue:e.target.value}) }; onExterClick =(value)=>{ console.log(`点击${value}` ); this.setState({refresh:!this.state.refresh}); }; render(){ return( <div> <div> <input value={this.state.value} onChange={this.OnChange(1)}/> </div> <div> <button onClick={()=>this.onClick(2)}>11</button> </div> <Demo2 externalValue={this.state.externalValue} OnExterChange={this.OnExterChange} onExterClick={this.onExterClick}/> </div> ); } } class Demo2 extends Component{ constructor(props){ super(props); } OnChange = value =>(e)=>{ this.props.OnExterChange(value ,e); }; render(){ return ( <div> <div> <input value={this.props.externalValue} onChange={this.OnChange(3)}/> </div> <div> <button onClick={()=>this.props.onExterClick(4)}>11</button> </div> </div> ) } }无默认情况下组件间、组件内差别不大。有默认参数时先把默认参数‘拿出来’
OnChange = value =>(e)=>{
this.props.OnExterChange(value ,e);
};
再传给父组件