将道具从父组件动态传递到子组件

时间:2020-07-21 12:47:59

标签: reactjs react-native

我有一个子组件StepperNotification,它从用户处获取输入,并以以下方式将其作为prop返回给其子组件。

const styles = {
    transparentBar: {
        backgroundColor: 'transparent !important',
        boxShadow: 'none',
        paddingTop: '25px',
        color: '#FFFFFF'
    }
};


const useStyles = makeStyles((theme: Theme) =>
    createStyles({
        formControl: {
            margin: theme.spacing(1),
            minWidth: 120,
        },
        selectEmpty: {
            marginTop: theme.spacing(2),
        },
    }),
);

function getSteps() {
    return ['Create', 'Audience', 'Timing'];
}

function getStepContent(step, $this) {


    switch (step) {
        case 0:
            return (
                <div className="row">
                    <CardBox styleName="col-lg-12"
                             heading="">
                        <form className="row" noValidate autoComplete="off" style={{"flex-wrap":"no-wrap", "flex-direction": "column" }}>
                            <div className="col-md-12 col-12">
                                <TextField
                                    id="campaign_name"
                                    label="Campaign Name"
                                    value={$this.state.name}
                                    onChange={$this.handleChange('name')}
                                    margin="normal"
                                    fullWidth
                                />
                            </div>
                        </form>
                    </CardBox>
                    
                </div>
                );
        default:
            return 'Unknown step';
    }
}

class NotificationStepper extends React.Component {
    state = {
        activeStep: 0,
        name: '',
    };

    handleChange = name => event => {
        this.setState({
            [name]: event.target.value,
        });
        this.props.titlechange(event.target.value);
    };


    handleNext = () => {
        this.setState({
            activeStep: this.state.activeStep + 1,
        });
    };

    handleBack = () => {
        this.setState({
            activeStep: this.state.activeStep - 1,
        });
    };

    handleReset = () => {
        this.setState({
            activeStep: 0,
        });
    };

    render() {
        const steps = getSteps();
        const {activeStep} = this.state;

        return (
            <div className="col-xl-12 col-lg-12 col-md-7 col-12">
                <Stepper className="MuiPaper-root-custom" activeStep={activeStep} orientation="vertical">
                    {steps.map((label, index) => {
                        return (
                            <Step key={label}>
                                <StepLabel>{label}</StepLabel>
                                <StepContent className="pb-3">
                                    <Typography>{getStepContent(index, this)}</Typography>
                                    <div className="mt-2">
                                        <div>
                                            <Button
                                                disabled={activeStep === 0}
                                                onClick={this.handleBack}
                                                className="jr-btn"
                                            >
                                                Back
                                            </Button>
                                            <Button
                                                variant="contained"
                                                color="primary"
                                                onClick={this.handleNext}
                                                className="jr-btn"
                                            >
                                                {activeStep === steps.length - 1 ? 'Finish' : 'Next'}
                                            </Button>
                                        </div>
                                    </div>
                                </StepContent>
                            </Step>
                        );
                    })}

                </Stepper>
                {activeStep === steps.length && (
                    <Paper square elevation={0} className="p-2">
                        <Typography>All steps completed - you&quot;re finished</Typography>
                        <Button onClick={this.handleReset} className="jr-btn">
                            Reset
                        </Button>
                    </Paper>
                )}


            </div>

        );
    }
}

export default NotificationStepper;

在我的父组件中,我正在获取此prop值并将其按以下方式传递给另一个子组件Tabcomponent

ParentCompoennt.js

const SendNotification = ({match}) => {

    let titlename = '';
    let message = '';

    function handleTitle(title_) {
        console.log('in here');
        console.log(title_);
        titlename = title_;
    }
    return (

        <div className="dashboard animated slideInUpTiny animation-duration-3">

            <ContainerHeader match={match} title={<IntlMessages id="sidebar.notification"/>}/>
            <div className="row" style={{'flex-wrap': 'no wrap', "flex-direction": 'row'}}>

                <div className="col-xl-7 col-lg-7 col-md-7 col-7">

                    <NotificationStepper titlechange={handleTitle} />
                    <div className='flex-class' style={{'width': '100%'}}>
                        <Button color="primary" style={{"align-self": "flex-end", "border" : "1px solid", "margin-left": "10px", "margin-bottom": "40px"}} size="small" className="col-md-2 col-2">Fetch</Button>
                        <Button color="primary" style={{"align-self": "flex-end", "border" : "1px solid", "margin-left": "10px", "margin-bottom": "40px"}} size="small" className="col-md-2 col-2" color="primary">Discard</Button>
                    </div>
                </div>
                <div className="col-xl-5 col-lg-5 col-md-5 col-5" style={{"padding-top": "20px"}}>
                    <span style={{"margin-left" : "20px", "font-weight": "bold"}}>Preview</span>
                    <TabComponent  {...{[title]:titlename}} message={message} />
                </div>

            </div>

        </div>
    );
};

export default SendNotification;

在TabComponent中,我正在获取此prop值,并以以下方式使用它

TabContainer.propTypes = {
    children: PropTypes.node.isRequired,
    dir: PropTypes.string.isRequired,
};

class TabComponent extends Component {
    state = {
        value: 0,
    };


    render() {
        const {theme} = this.props;
        const title = this.props.title;


        return (
            <div className="col-xl-12 col-lg-12 col-md-12 col-12" style={{"margin-top": "15px"}}>
                    <NotifCard  key={0} data={{'name': title, 'company': 'sayge.ai', 'image': require("assets/images/bell.png"), 'description': this.props.message}} styleName="card shadow "/>
                    
            </div>
        );
    }
}

TabComponent.propTypes = {
    theme: PropTypes.object.isRequired,
};

export default withStyles(null, {withTheme: true})(TabComponent);

StepperNotification运行正常,并且正在父级中更新道具。我已经通过在控制台中打印更新的值进行了检查,但是TabComponent中的道具没有被更新。我在这里做错了什么?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

可能这是您的问题

<TabComponent  {...{[title]:titlename}} message={message} />` this could be just 

title未定义,您正在发送props[undefined]=titlename

只需这样做

<TabComponent title={titlename} message={message} />`

如果SendNotification是反应功能组件useState,用于跟踪当前标题名称。如果在第一次修复后仍然无法正常工作,则此秒将是您遇到问题的另一个原因。