簡體   English   中英

react-router如何將prop傳遞給其他組件 <Links> 和 <Route> ?

[英]How does react-router pass props to other components with <Links> and <Route>?

我有一個選擇輸入來在PageA1中創建newCountry的值。我想將此值傳遞給PageB。但是控制台會警告: [react-router] You cannot change <Router routes>; it will be ignored 當我選擇newCountry時[react-router] You cannot change <Router routes>; it will be ignored

如何使用<Links><Route>傳遞newCountry的值?

PageA.js:

 export default class PageA extends Component{
      constructor(props){
        super(props);
        this.state = {
          country:''
        }
      }

  // 收取country的callback
  selectCountry = (newCountry)=>{
    this.setState({country:newCountry});
    this.props.callbackPageA(newCountry);
  }

  render(){
    return(
      <div>
        <div>
          <PageA1 callbackCountry={this.selectCountry} />
        </div>
      </div>
    );
  }
}

我的路由器App.js:

export default class App extends React.Component {
  constructor(props){
    super(props);
    this.state={
      country:''
    }
  }
  PageAValue = (newCountry) =>{
    this.setState({
      country:newCountry
    })
  }
  render () {
    const CountryProps = this.state.country;
    console.log('app '+CountryProps);
    return(
      <Router history={browserHistory}>
        <Route path="/" component={HomePage}></Route>
        <Route path="/PageA" component={() => <PageA callbackPageA={this.PageAValue}/>}></Route>
        <Route path="/PageB" component={PageB}  CountryProps={CountryProps}>
        </Route>
      </Router>
    )
  }
}

PageB.js:

export default class PageB extends React.Component {
  constructor(props){
    super(props);
  }
  render () {
    const country = this.props.route.CountryProps;
    console.log('corepage ' + country);

    return(
      <div>
        <div>
          <div><PageD country={country}/></div>
        </div>
      </div>
    )
  }
}

您可以將state附加到位置描述符 例如,你可以定義to支撐用於<Link>為:

<Link to={{ pathname: '/PageB', state: { country: 'Ireland' }}} />

然后在您的PageB組件中,該location將作為prop可用。

<Route>組件純粹是用於配置,實際上並未呈現,這就是為什么您收到該警告的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM