这里组件间参数传递只介绍利用回调传递(ref不介绍)即子组件向父组件传值。(父组件向子组件传值用props,层级较深或无关联组件间传参即需要全局数据管理参考react-redux、MobX等)
组件内(无默认参值和需要默认参值情况)
class Demo extends Component{
constructor(props){
super(props);
this.state={
value:'',
externalValue:''
};
}
onClick = (value) =>{
console.log(`点击${value}` );
this.forceUpdate();
};
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>
);
}
}
注意两种情况为避免函数立即执行的写法
组件间(无默认参值和需要默认值情况)
class Demo extends Component{
constructor(props){
super(props);
this.state={
value:'',
externalValue:''
};
}
onClick = (value) =>{
console.log(`点击${value}` );
this.forceUpdate();
};
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.forceUpdate();
};
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);
};
//方式相同
function onChange (value) {
return function(e) {
this.props.OnExterChange(value, e);
}
}