在REACT中将属性/功能从父级传递给子级

时间:2017-09-07 18:33:32

标签: javascript reactjs react-router react-redux frontend

我正在尝试将一些属性和函数从名为 Layout 的反应父组件传递给 routes.tsx 中定义为此的所有子组件:

export const routes = <Layout>
    <Route exact path='/' component={ Home } />
    <Route path='/createSession' component={ CreateSession } />
    <Route path='/questions' component={Questions} />
    <Route path='/summary' component={Summary} />
</Layout>;

在布局组件中,我正在尝试添加这样的自定义参数:

const childWithProp = React.Children.map(this.props.children, (child) => {
            return React.cloneElement(React.Children.only(child), { add: this._onSubmit, reservations: someValue });
        });

但是在名为 Questions 的子组件中,即使我具有与父项中导出的同名属性,它也是未定义的。以下是儿童代码的一部分:

interface QuestionsCustomProps {
    reservations: string;
    add: Function;
}

type QuestionsProps =
    GlobalStore.GlobalState
    & QuestionsCustomProps
    & RouteComponentProps<{}>
    ;

class Questions extends React.Component<QuestionsProps, FetchDataExampleState> {
    constructor(props: QuestionsProps) {
        super(props);
        this.state = { collection: undefined, loading: true, showModal: false, modalErrorMessage: '' };

        this.handleErrors = this.handleErrors.bind(this);
        this.closeModal = this.closeModal.bind(this);


        this.getSpecificCollection = this.getSpecificCollection.bind(this);
        this.getFirstStep = this.getFirstStep.bind(this);

        /*if (typeof this.props.match.params.collectionId === 'undefined' || this.props.match.params.collectionId === null) {
            this.getFirstStep();
        }
        else {
            this.getSpecificCollection(this.props.match.params.collectionId);
        }*/

        if (this.props.sessionId !== '' && this.props.sessionId !== undefined) {
            if (this.state.collection === undefined) {
                this.getFirstStep(this.props.sessionId);
            }
            else {
                this.getSpecificCollection(this.state.collection.id, this.props.sessionId);
            }
        }
        //else {
        //    this.state = { collection: undefined, loading: false, showModal: true, modalErrorMessage: 'No session exists - create one first!' };
        //}

        //this.getData = this.getData.bind(this);
        this.handleFormSubmit = this.handleFormSubmit.bind(this);
        this.getPreviousStep = this.getPreviousStep.bind(this);
        this.componentWillReceiveProps = this.componentWillReceiveProps.bind(this);

    }

 public render .......
}

有没有其他方法可以使用 this.props.children 将params传递给孩子?非常感谢您的回复!

0 个答案:

没有答案