如何不使用form表单的情况下,子控件将值传递给父控件

诸葛非卿
  • 166

如标题所描述,我使用antd自定义了一个组件,父控件是在Form当中。
子控件在父控件中代码如下:

                      <Item name={'authorizationContent'} style={{marginTop:20,marginLeft:25,width:'100%',clear:'both',maxHeight:650,minHeight:330}} hidden={this.state.showDIVVisible}>
                            <ClassTableDiyShow />
                      </Item>

子控件如下:

import React,{useState} from "react";
import {Checkbox, Table,Divider,Tabs,DatePicker,TimePicker, Button,Form} from "antd";
import {MinusCircleOutlined, PlusOutlined,MinusOutlined} from "@ant-design/icons/lib";
import { getByTitle, render } from "@testing-library/react";
import { title } from "process";
import { setSateProperty } from "@/components/ProTable/reducers";
import locale from "antd/es/date-picker/locale/zh_CN";
import 'moment/locale/zh-cn';
const {TabPane} =Tabs;
const { RangePicker } = TimePicker;
const tabHeader=['星期一','星期二','星期三','星期四','星期五','星期六','星期日'];
const Item =[
    [{key:0,value:0,show:true}],
    [{key:0,value:0,show:true}],
    [{key:0,value:0,show:true}],
    [{key:0,value:0,show:true}],
    [{key:0,value:0,show:true}],
    [{key:0,value:0,show:true}],
    [{key:0,value:0,show:true}]
];

let i=0;
let showFri:boolean=true;
const returnData:any=[];
const ClassTableDiyShow : React.FC<any>= (props) =>{
    const [device, setDevice] = React.useState<string[]>([]);
    const [value, setValue] = useState([]);
    const [item,setItem] =useState<number[]>([]);
    const [week,setWeek]=useState<string>("Mon");
    const onChange = (time:any,timeStr:any) => {
      returnData.push({
          "week":week,
          "time":timeStr
      })
      console.log(returnData);
    };
    const tabsOnChange=(e:any)=>{
        switch(e){
            case "0":
                setWeek("Mon");
            break;
            case "1":
                setWeek("Tue");
            break;
            case "2":
                setWeek("Wed");
            break;
            case "3":
                setWeek("Thu");
            break;
            case "4":
                setWeek("Fri");
            break;
            case "5":
                setWeek("Sta");
            break;
            case "6":
                setWeek("Sun");
            break;
        }
    }
    const addTimePanel= (e:number)=>{
        let nowIndex=i+1;
        Item[e].push({key:nowIndex,value:nowIndex,show:false})
        showFri=false;
        setItem([nowIndex]);
    };
    const deleteTimePanel= (e:number,ex:number)=>{
         Item[e].splice(ex,3);
         setItem([ex]);
    }
   
        return(
            <div>
                <Tabs defaultActiveKey="0" tabPosition={'top'} style={{minHeight:220}} onChange={(e:any)=>{tabsOnChange(e)}}>
                    {[...Array.from(tabHeader,i=>i)].map((i,index)=>(
                        <TabPane tab={i}  key={index}>
                            <div style={{textAlign:'left',width:350}}>
                                {[...Array.from(Item[index],m=>m)].map((m,ing)=> 
                                    <div>
                                        <RangePicker bordered={true} placeholder={['开始时间','结束时间']} onChange={onChange} style={{marginBottom:8}}  locale={locale}/> 
                                        <Button style={{width:'50',marginBottom: 8,marginLeft:5}} onClick={event => {deleteTimePanel(index,ing)}} hidden={m.show}><MinusOutlined /></Button>
                                    </div>
                                )}
            
                                    <div style={{textAlign:'center'}}>
                                         <Button style={{width: 50,marginRight:90}} onClick={event =>{addTimePanel(index)}}> <PlusOutlined style={{marginLeft:0}}/></Button>
                                    </div>
                            </div>

                        </TabPane>
                    ))}

                </Tabs>
            </div>    
        )
 
}

export default ClassTableDiyShow;

请问有什么方法实现该目的。

回复
阅读 253
2 个回答
✓ 已被采纳

1.使用Context这个特性,在父级定义一个Context,这个Context提供了变量和修改变量的方法给子组件,子孙组件直接拿来用就行了。好处是无论有多少层子组件,都可以直接使用。比如下面这样

// 父组件
import MyContext from 'myContext';

export default function Parent() {
    const [data, setData] = useState([]);
    const context = {
      data,
      setData
    };

    return (
        <MyContext.Provider value={context}> 
            <Child></Child>
        </MyContext.Provider>
    )
}
// 子组件
import MyContext from 'myContext';

export default function Child() {
    const { setData } = useContext(MyContext);
    
    function onChange(e){
        setData(e);
    }

    return (
        <Tab onChange={onChange}>...</Tab>
    )
}

2.父组件直接向子组件传递props方法,子组件通过props里的方法,把值传给父组件。比如

// 父组件
export default function Parent() {
    const [data, setData] = useState([]);
    return (
        <Child setData={setData}></Child>
    )
}
// 子组件
export default function Child(props) {
    const { setData } = props;
    
    function onChange(e) {
        setData(e);
    }

    return (
        <Tab onChange={onChange}></Child>
    )
}
zingwu
  • 2
新手上路,请多包涵

父组件传一个函数给子组件,子组件通过 callback 的方式返回给父组件,把 callback 放在父组件执行就好了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏