如何将道具传递给React中的组件

时间:2019-03-07 03:07:34

标签: reactjs react-component

我有2个页面组件,它们都有自己的路线。在两个页面中都将使用一个标头组件,并且应该根据您所在的页面来更改其内容。

如何更改每页标题中的内容?

 return (
        <main className={theme.main}>
            <Header 
                title={this.state.headerTitle}
                boldTitle={this.state.boldTitle}
            />
            <div className={theme.content}>
                <Switch>
                    <Route path={'/page1'} component={Page1} />
                    <Route path={'/page2'} component={Page2} />
                </Switch>
            </div>
            <Footer/>
        </main>
    );

我正尝试将道具传递到“路线”页面的标题,如以下代码所示。

<Route path={'/page2'} component={Page2} currentTitle={this.state.headerTitle} />

更新

我使用 import { withRouter } from "react-router";

export default withRouter(Header);

在标头组件中,然后他侦听路由,然后我可以输入路径名以执行我需要的操作。

然后,我不需要设置状态,只需侦听MyComponent内的路由即可。 Usign:this.props.location

4 个答案:

答案 0 :(得分:0)

在页1和页2中移动标题。

<Route path={'/page2'} component={() => <Page2  currentTitle={this.state.headerTitle} 
 />} />

然后在标题中使用currentTitle更改标题。

答案 1 :(得分:0)

将页眉放入其自己的组件中,并将其分别导入每个页面组件中。

然后,当您在每个页面中调用Header时,就可以像这样将props传递到header中。

import Header from (wherever that component is)

class Page# extends React.component {

other code

render() {
return (
         <div>
           <Header currentTitle="this.state.headerTitle" />
           <rest of code for this page /> 
         </div> 
}

或您需要的任何道具。

答案 2 :(得分:0)

我假设您显示的代码位于某些React组件的render()方法内部,因此您实际上具有状态。

请注意,component标记中的Route属性需要一个不带参数的函数值。要呈现的组件是函数的结果。但没有什么可以阻止您在返回值之前 进行一些工作。我会尝试这样的事情

<Route path={'/page1'} component={() => {
    this.setState({headerTitle: ...what you want..., boldTitle: ...what you want...})
    return <Page1 />
}}/>

如果Page1只是一个函数,请用return Page1()更改“返回”行

希望有帮助-卡洛斯(Carlos)

答案 3 :(得分:0)

您可以将redux库用作全局状态

类似的东西

v1.2.3

第1页

 class Main extends Component{
    render(){
    return (
            <main className={theme.main}>
                <Header 
                    title={this.props.headerTitle}
                    boldTitle={this.state.boldTitle}
                />
                <div className={theme.content}>
                    <Switch>
                        <Route path={'/page1'} component={Page1}/>
                        <Route path={'/page2'}component={Page2}
                        />
                    </Switch>
                </div>
                <Footer/>
            </main>
        )
    }
    const mapStateToProps = state =>{
     return {     headerTitle: state.headerTitle    }
    }
    export default connect(mapStateToProps)(Main)

代码不起作用,但这是一个想法,您可以如何为此目的使用redux