React 组件内、组件间传值

这里组件间参数传递只介绍利用回调传递(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(
            
); } }

注意两种情况为避免函数立即执行的写法

组件间(无默认参值和需要默认值情况)

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(
            
); } } class Demo2 extends Component{ constructor(props){ super(props); } OnChange = value =>(e)=>{ this.props.OnExterChange(value ,e); }; render(){ return (
) } }

无默认情况下组件间、组件内差别不大。有默认参数时先把默认参数‘拿出来’    再传给父组件

onChange = value =>(e)=>{
      this.props.OnExterChange(value, e);
};
//方式相同
function onChange (value) {
    return function(e) {
         this.props.OnExterChange(value, e);
    }
}

 

你可能感兴趣的:(react)