React三大屬性之一props

組件實對象3大屬性之一:props屬性

1.每個組件對象都會有props(properties的簡寫)屬性
2.組件標籤的所有屬性都保存在props中
3.內部讀取某個屬性值:this.props.propertyName
4.作用:通過標籤屬性從組件外 向組件內傳遞數據(只讀 read only)
5.對props中的屬性值進行類型限制和必要性限制

Person.propTypes = {
      name: React.PropTypes.string.isRequired,
      age: React.PropTypes.number.isRequired
 }

6.擴展屬性:將對象的所有屬性通過props傳遞

<Person {...person}/>

7.默認屬性值

Person.defaultProps = {
      name: 'Mary'
};

8.組件類的構造函數

constructor (props) {
      super(props);
      console.log(props); // 查看所有屬性
    }

舉個例子(拆分兩個組件 父組件給子組件傳遞參數和方法)

  • 簡單的一個修改的組件demo 如有不懂可以聯繫留言
import React,{Component} from 'react';

import axios from "axios";
import {Button, Modal, Form, Input, Radio, Select, DatePicker, Icon, Upload, message, Row, Col,Checkbox} from 'antd';
import moment from "moment";

const { Option } = Select;

const CollectionCreateForm = Form.create({ name: 'form_in_modal' })(
    // eslint-disable-next-line
    //子類組件
    class extends React.Component {
        render() {
        //解構賦值 拿到父類的方法 和參數
            const { visible, onCancel, onCreate, form ,dataInfo,foodList,addImg} = this.props;
           const props = {
                name: 'imgFile',
                    action: 'http://localhost:8080/react_navlink/foot/uploadPic.do',
                    headers: {
                    authorization: 'authorization-text',
                },
                onChange(info){
                    if (info.file.status !== 'uploading') {
                        console.log(info.file, info.fileList);
                    }
                    /*圖傳上傳成功*/
                    if (info.file.status === 'done') {
                        message.success(`${info.file.name} file uploaded successfully`);
                       // console.log(info.file.response.errorCode)
                        const imgs =info.file.response.errorCode
                        {
                        //調用父類傳遞過來的方法
                            addImg(imgs)
                        }

                        /*圖片上傳失敗*/
                    } else if (info.file.status === 'error') {
                        message.error(`${info.file.name} file upload failed.`);
                    }
                },
            };
            const { getFieldDecorator } = form;
            /*console.log(dataInfo)*/
            return (
                <Modal
                    visible={visible}
                    title="Create a new collection"
                    okText="修改"
                    onCancel={onCancel}
                    onOk={onCreate}
                >
                    <Form layout="vertical">
                        <Form.Item label="菜名">
                            {getFieldDecorator('footName',
                                {
                                //dataInfo 是父類傳遞過來的值
                                    initialValue: dataInfo.footName, /*默認值*/
                                },
                                {
                                    rules: [{ required: true, message: 'Please input the title of collection!' }], /*這裏設置了驗證條件*/
                                })(<Input />)}
                        </Form.Item>

                        <Form.Item label="評論">
                        {getFieldDecorator('footContent',
                            {
                                initialValue: dataInfo.footContent, /*默認值*/
                            },
                            {
                                rules: [{ required: true, message: 'Please input the title of collection!' }], /*這裏設置了驗證條件*/
                            })(<Input type="textarea" />)}
                         </Form.Item>

                        <Form.Item label="圖片">
                            <div><img src={"http://localhost:8080/react_navlink/foot/readPic.do?footImg="+this.props.footImg} alt="圖片展示"/></div>
                            {getFieldDecorator('footImg',
                                {
                                    initialValue: dataInfo.footImg, /*默認值*/
                                },
                                {
                                    rules: [{ required: true, message: 'Please input the title of collection!' }], /*這裏設置了驗證條件*/
                                })(<Upload {...props}>
                                <Button>
                                    <Icon type="upload" /> Click to Upload
                                </Button>
                            </Upload>)}
                        </Form.Item>
                        {/*單選*/}
                        <Form.Item label="是否開售">
                            {getFieldDecorator('footType',
                                {
                                    initialValue:dataInfo.footType, /*默認值*/
                                },)(<Radio.Group>
                                        <Radio value={1}>是</Radio>
                                        <Radio value={2}>否</Radio>
                                </Radio.Group>
                                )}
                        </Form.Item>
                        <Form.Item label="配菜">


                            {getFieldDecorator('footPage',
                                {
                                    initialValue:dataInfo.footPage.split(","), /*默認值*/
                                },)(<Checkbox.Group style={{ width: '100%' }} >
                                    <Row>
                                        <Col span={8}>
                                            <Checkbox value="1">腐竹</Checkbox>
                                        </Col>
                                        <Col span={8}>
                                            <Checkbox value="2">豆皮</Checkbox>
                                        </Col>
                                        <Col span={8}>
                                            <Checkbox value="3">土豆</Checkbox>
                                        </Col>
                                        <Col span={8}>
                                            <Checkbox value="4">娃娃菜</Checkbox>
                                        </Col>
                                        <Col span={8}>
                                            <Checkbox value="5">香菇</Checkbox>
                                        </Col>
                                    </Row>
                                </Checkbox.Group>
                            )}
                        </Form.Item>
                        {/*時間*/}
                        <Form.Item label="上市時間">
                            {getFieldDecorator('footDate',
                                {
                                    initialValue:moment(dataInfo.footDate),
                                })
                            (<DatePicker/>)}
                        </Form.Item>

                        {/*菜系*/}
                        <Form.Item className="collection-create-form_last-form-item">
                            {getFieldDecorator('footStyleId', {
                                initialValue: dataInfo.footStyleId, /*默認值*/
                            })(
                                <Select style={{ width: 120 }} >
                                    {
                                        foodList.map((value,index)=>{
                                            return <Option key={index} value={value.styleId}>{value.styleName}</Option>
                                        })
                                    }

                                </Select>
                            )}
                        </Form.Item>

                    </Form>
                </Modal>
            );
        }
    },
);


//父類組件
export default class Update extends Component{

    state = {
        dataInfo:{
            footStyleId:"",
            footName:"",
            footDate:"",
            footPage:"",
            footImg:"",
            footContent:"",
            footType:"",
        },
        foodList:[],
        visible: false,


    };

    addImg=(img)=>{
        console.log(img)
        this.setState({
            footImg:img,
        })
    }

    /*顯示修改數據*/
    showModal = () => {
        this.queryData();
        this.setState({ visible: true });
    };

    /*關閉修改界面*/
    handleCancel = () => {
        const { form } = this.formRef.props;
        form.resetFields();
        this.setState({ visible: false });
    };

    /*點擊修改事件*/
    handleCreate = () => {
        const { form } = this.formRef.props;
        console.log(form);
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            let footChecked = "";
            values.footPage.map((value,index)=>{
                footChecked+=value+","
            })
            console.log(footChecked)
            /*修改路徑*/
            axios.post("http://localhost:8080/react_navlink/foot/updateData.do",{
                footId:this.props.footId,
                footName:values.footName,
                footContent:values.footContent,
                footStyleId:values.footStyleId,
                footImg:this.state.footImg,
                footPage:footChecked,
            }).then(resp=>{
                this.props.queryListFoot();
            }).catch(resp=>{

            })

            form.resetFields();
            this.setState({ visible: false });
        });
    };

    saveFormRef = formRef => {
        this.formRef = formRef;
    };

    /*查詢*/
    queryData=()=> {
        const footId = this.props.footId;
        console.log(footId)
        axios.get("http://localhost:8080/react_navlink/foot/updeInfo.do?footId="+footId)
            .then(resp=>{
                this.setState({
                    dataInfo:resp.data,
                })
            }).catch(resp=>{
            alert("回顯失敗")
        })
    }

   componentDidMount() {
        axios.get("http://localhost:8080/react_navlink/style/queryList.do").
        then(resp=>{
            this.setState({
                foodList:resp.data,
            })
        }).catch(resp=>{
            alert("失敗");
        })
    }



    render() {
        return(
            <div>

                <Button type="primary" onClick={this.showModal}>
                    修改
                </Button>
                {/*收集表單元素*/}
                //給子類組件傳遞方法和參數
                <CollectionCreateForm foodList={this.state.foodList}
                                      wrappedComponentRef={this.saveFormRef}
                                      visible={this.state.visible}
                                      onCancel={this.handleCancel}
                                      onCreate={this.handleCreate}
                                      dataInfo={this.state.dataInfo}
                                      addImg={this.addImg}
                />

            </div>
        );
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章